Function template does not recognize lvalue value

I have a problem in my code

Here is a simplified version:

#include <iostream> class A { public : template <class T> void func(T&&)//accept rvalue { std::cout<<"in rvalue\n"; } template <class T> void func(const T&)//accept lvalue { std::cout<<"in lvalue\n"; } }; int main() { A a; double n=3; a.func(n); a.func(5); } 

I expect the output to be:

 in lvalue in rvalue 

but this

 in rvalue in rvalue 

why?!

+5
c ++ c ++ 11 templates rvalue lvalue
source share
3 answers

template <class T> void func(T&&) is a reference link for a universal link .

To check what you want try: ( Live example )

 template <typename T> class A { public: void func(T&&)//accept rvalue { std::cout<<"in rvalue\n"; } void func(T&)//accept lvalue { std::cout<<"in lvalue\n"; } }; int main() { A<double> a; double n = 3; a.func(n); a.func(5.); } 
+7
source share

To build the perfect answer on Jarod42, if you want to preserve the design of the main function template, you can decide based on the type of universal reference parameter deduced:

 #include <iostream> #include <type_traits> struct A { template <typename T> // T is either U or U & void func(T && x) { func_impl<T>(std::forward<T>(x)); } template <typename U> void func_impl(typename std::remove_reference<U>::type & u) { std::cout << "lvalue\n"; } template <typename U> void func_impl(typename std::remove_reference<U>::type && u) { std::cout << "rvalue\n"; } }; 
+6
source share

I think the surprise comes from how template arguments are derived. You will get what you expect if you write:

 a.func<double>(n); 
+2
source share

All Articles