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?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
01000001
  • 833
  • 3
  • 8
  • 21

1 Answers1

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

101010
  • 41,839
  • 11
  • 94
  • 168
  • This is perfectly working. But what if i want to have two saperate print functions?? Or is it stupid thing to do?? – 01000001 Jun 10 '15 at 22:00
  • 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. – 101010 Jun 10 '15 at 22:02
  • I am trying to have two saperate templates for both print functions one with T& and other with T&& but its not working. – 01000001 Jun 10 '15 at 22:04
  • Yeap, with templates won't work cause the compiler due to certain C++ standard rules can't distinguish between the two overloads. – 101010 Jun 10 '15 at 22:06
  • Then i guess i will have to live with only one print.. Anyway thank you so much. :) :) – 01000001 Jun 10 '15 at 22:08