3

I have the following code.

#include <iostream> using namespace std; void print(int& number){ cout<<"\nIn Lvalue\n"; } void print(int&& number){ cout<<"\nIn Rvalue\n"; } int main(int argc,char** argv){ int n=10; print(n); print(20); } 

It works fine. But I want to make a function template so that it accepts both lvalues and rvalues. Can anyone suggest how to do it?

1 Answer 1

1

Unless you want to change the input argument a const lvalue reference will do the job because rvalue references can bind to const lvalue references:

void print(int const &number) { ... } 

LIVE DEMO

Nevertheless, You could just:

template<typename T> void print(T &&number) { ... } 

LIVE DEMO

Sign up to request clarification or add additional context in comments.

5 Comments

This is perfectly working. But what if i want to have two saperate print functions?? Or is it stupid thing to do??
If you want to have two separate print functions then you should have two overloads as in your example. However, from a practical point of view if you only want to print (i.e., not alter the input argument), a single function with input argument a const lvalue reference is sufficient.
I am trying to have two saperate templates for both print functions one with T& and other with T&& but its not working.
Yeap, with templates won't work cause the compiler due to certain C++ standard rules can't distinguish between the two overloads.
Then i guess i will have to live with only one print.. Anyway thank you so much. :) :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.