5

I have a problem in my code

Here is simplified version of it :

#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 it is

in rvalue in rvalue 

why ?!

1
  • 3
    Hint: what's the difference between both parameters, aside the &? Commented Mar 4, 2014 at 8:40

3 Answers 3

7

template <class T> void func(T&&) is universal reference forwarding reference.

To test 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.); } 
Sign up to request clarification or add additional context in comments.

3 Comments

Maybe "universal reference" should be in quotes, since it is not a language construct.
@juanchopanza Technically, it is a language construct, just that "universal reference" is not its official name. I quite wish it were, though.
It is now called "forwarding reference".
6

To build on Jarod42's fine answer, if you want to keep the design of having a primary function template, you can decide based on the deduced type of the universal reference parameter:

#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"; } }; 

Comments

2

I think the surprise comes from the way the template argument are deduced. You'll get what you expect if you write:

a.func<double>(n); 

2 Comments

I think you mean "how function template arguments are deduced".
Yes ! I realized that I don't fully understand what's going on here. I asked a followup question: stackoverflow.com/questions/22167235/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.