Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to avoid duplicated code while creating a function in rvalue and lvalue references?

Tags:

c++

templates

Sometimes when i'm creating a function it needs a rvalue reference version, as example:

template<typename T> void printCont(T &Cont){
    for (auto &i : Cont)
        cout << i << ' ';
    cout << endl;
}

So i can print any container like std::vector but i would need to manage some rvalues to be printed directly

template<typename T> void printCont(T &&Cont){
    for (auto &i : Cont)
        cout << i << ' ';
    cout << endl;
}

So i can call it as printCont(myclass.getVector()) as example. (in this example would be to easy to just copy the content to print in this version, to a lvalue vector, but in real world programs, do this would make our program slower)

But as you can see, BOTH FUNCTIONS HAVE THE SAME CODE. Is i know, duplicated code is a mistake in good practices. So my question is about... is there a way to call the lvalue version of the function from the rvalue version or viseversa? Is there a way to avoid this duplicated code? Imagine i create two 2000lines function and i need to create both version of it, it would be a waste of lines just do "Control+C" and "Control+V".

like image 790
AlexanderFedoosev789 Avatar asked Oct 15 '25 02:10

AlexanderFedoosev789


1 Answers

For the second function:

template<typename T> void printCont(T &&Cont)

it is actually a forwarding reference, which means it can be called with both lvalue and rvalue arguments. If called with an lvalue then T deduces to lvalue reference type. You can remove the first version from your code.


Another option, since your code does not modify the operand, is to use:

template<typename T> void printCont(T const& Cont)

which also will accept both lvalues and rvalues.


(in this example would be to easy to just copy the content to print in this version, to a lvalue vector, but in real world programs, do this would make our program slower)

This makes no sense, it seems you have some misunderstanding about lvalues and rvalues.

like image 106
M.M Avatar answered Oct 18 '25 04:10

M.M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!