Re: Question on type deduction
francis_r wrote:
void Augment( int& outNumber )
{
outNumber++;
}
template< typename ReturnType, typename Type1 >
ReturnType ExecuteFunction( ReturnType (*inFunction)( Type1 ), Type1
inArg1 )
{
return inFunction( inArg1 );
}
int main()
{
int theNumber = 10;
ExecuteFunction( Augment, theNumber ); // <-- compiler error
ExecuteFunction< void, int& >( Augment, theNumber ); // compiles OK
}
The compiler deduces the parameters from each of the arguments
independently. From the first one, it deduces ReturnType=void and
Type1=int& ; from the second one it can only deduce Type1=int.
These two results are incompatible, so the deduction fails.
It seems that the second argument (theNumber) is not passed by
reference even though the Augment requests int& explicitely.
Is there a way I can rewrite the function ExecuteFunction so that I can
call it without having to explicitely specify it's template parameters?
If so, how?
Yes, try this:
template <typename T>
struct identity { typedef T type; };
template <typename R,typename A>
R exec(R (*fn)(A),typename identity<A>::type a) { return fn(a); }
void foo(int& a) { }
int main(){
int i=0;
exec(foo,i);
}
Here the second parameter of exec does not participate in the
deduction at all.
Cheers,
Vladimir Marko
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]