Search code examples
c++c++11rvalue-referenceoverloadingfunction-templates

Function overloading with template


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?


Solution

  • 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