The template argument loses the lvalue link if not used directly

Consider this code:

#include <iostream> #include <type_traits> using namespace std; template<typename T_orig> void f(T_orig& a){ a=5; } template<typename T_orig, typename T=T_orig&> void g(T a){ a=8; } int main() { int b=3; f<decltype(b)>(b); cout<<b<<endl; g<decltype(b)>(b); cout<<b<<endl; return 0; } 

Will print

 5 5 

Can someone explain to me why the second version gets lost & ?

+7
source share
1 answer

The problem is that type inference takes precedence over default function template parameters. So you get the parameter T , and T never displays a link.

You can prevent this by making the type non-deducible . A common identifier type attribute can do this.

 template <typename T> struct identity { using type = T; }; template <typename T> using NotDeducible = typename identity<T>::type; template<typename T_orig, typename T=typename target<T_orig>::T> void g(NotDeducible<T> a) { // blah 

Or, in this particular case, you can just completely get rid of the template parameter.

 template<typename T_orig> void g(typename target<T_orig>::T a) 
+12
source

All Articles