Function overloading with template

107 views Asked by At

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

There are 1 answers

5
101010 On BEST ANSWER

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