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?
Thanks in advance for all helpful feedback.
Kind regards,
Francis
Look at the types involved in the call that doesn't work:
ExecuteFunction( Augment, theNumber ); // <-- compiler error
Augment is a pointer to a function that takes an int& and returns void.
theNumber is an int.
So, the generated instance of ExecuteFunction will look like this:
void ExecuteFunction( void (*inFunction)( int& ), int inArg1 )
{
return inFunction( inArg1 );
}
Hopefully the problem is now obvious: inArg1 is an int, which cannot be
converted to an int& for the call to inFunction.
To be honest, the use of an int& is not really good style anyway: given the
calling site, how is the poor maintenance programmer supposed to know that
calling ExecuteFunction() is going to alter the value of theNumber? Yes,
they can work it out by looking at the definition of Augment, but you are
just setting traps for the unwary, which won't earn you any friends when
the pressure is on to iron out the last few bugs and ship the product.
The good news is that if you remove the use of int&, you not only make the
code more obvious, you solve the compilation problem as well. Either
replace the int& with an int*, so that the calling site becomes
ExecuteFunction( Augment, &theNumber );
or adopt a more value based approach (which will sit better with the STL)
and change Augment to return the altered value instead:
int Augment( int num )
{
return( num + 1 );
}
This also yields a more readable calling site:
int theNumber = 10;
theNumber = ExecuteFunction( Augment, theNumber );
Ian
-- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]