f



Template type deduction failure when using reference types

Hello all,
Can anyone help me with a particularly obscure error? The following
code fails to compile on g++

template<typename retT, typename argT>
void func(retT (*funcPtr)(argT), argT argument)
{}

void func1(int a) {}
void func2(int& a) {}

int main()
{
 int val = 1;
 int& valref = val;

 func(&func1, valref);//Succeeds
 func(&func2, valref);//Fails
}

The compiler appears to lose the ampersand from argT when it creates
the function. I'm completely stuck on this one so any help would be
greatly appreciated.
Thanks,
Marcus

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
8/3/2010 6:18:33 AM
comp.lang.c++.moderated 10738 articles. 1 followers. allnor (8509) is leader. Post Follow

1 Replies
663 Views

Similar Articles

[PageSpeed] 14

Marcus wrote:

> Hello all,
> Can anyone help me with a particularly obscure error? The following
> code fails to compile on g++
> 
> template<typename retT, typename argT>
> void func(retT (*funcPtr)(argT), argT argument)
> {}
> 
> void func1(int a) {}
> void func2(int& a) {}
> 
> int main()
> {
>  int val = 1;
>  int& valref = val;
> 
>  func(&func1, valref);//Succeeds
>  func(&func2, valref);//Fails
> }
> 
> The compiler appears to lose the ampersand from argT when it creates
> the function. I'm completely stuck on this one so any help would be
> greatly appreciated.

"argT" is deduced to different types in the second function call. It's "int"
for the right function parameter, but it is "int&" for the left function
parameter. Thus you have a contradiction, and type deduction fails.

You are going to need to make the left parameter a non-deduced context so
that it won't participate

template<typename T> struct identity { typedef T type; };

template<typename retT, typename argT>
void func(retT (*funcPtr)(argT), typename identity<argT>::type argument)
{}


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Johannes
8/3/2010 3:23:07 PM
Reply: