Re: Question on type deduction
francis_r wrote:
Following very simplified code will illustrate my problem:
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
}
Compiler error goes as follows:
function call
ExecuteFunction({lval} void (int &), {lval} int)' does not match
'ExecuteFunction<...>(__T0 (*)(__T1), __T1)'
on line 435 ExecuteFunction( Augment, theNumber );
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?
The problem is that argument deduction mechanism is trying to deduce
the actual type of Type1 template parameter from both actual parameters
of ExecuteFunction instantiation. From the first argument it is 'int &'
but from the second it's 'int', so the deduction fails. You could try
to introduce a nondeducible context for the second parameter which will
limit deduction to the first argument only:
template <typename T>
struct wrapper
{
typedef T type;
};
template< typename ReturnType, typename Type1 >
ReturnType ExecuteFunction( ReturnType (*inFunction)( Type1 ), typename
wrapper<Type1>::type inArg1 )
{
return inFunction( inArg1 );
}
Regards,
Przemek.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]