Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Too many copies of the function to use std::move in C++

I have 2 classes: A and B. I need to pass instances of them to a function that will push them into a vector. I want to have good efficiency in my program, so I try to use move semantics. So in that function I need const A& and A&& type for A as well as for B.
It forces me to create 2^N number of functions where N is the number of parameters to that function. In my case N is 2 and this means that I need to create 4 almost identical copies of the function.
Code:

struct A {
    std::vector<int> v;
};

struct B {
    std::vector<int> v;
};

static std::vector<std::pair<A, B>> elements;

void Function(const A &a, const B &b) {
    elements.emplace_back(a, b);
}

void Function(A &&a, const B &b) {
    elements.emplace_back(std::move(a), b);
}

void Function(const A &a, B &&b) {
    elements.emplace_back(a, std::move(b));
}

void Function(A &&a, B &&b) {
    elements.emplace_back(std::move(a), std::move(b));
}

The code is simplified. In my real code, the Function is bigger.
So, I want to know if there is another, better way of doing this?
Hope for your help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can create a template function and use std::forward to pass on the value with the correct reference type:

template<class T, class U>
void Function(T&& a, U&& b) // note: universal references are used here, not rvalue references
{
    elements.emplace_back(std::forward<T>(a), std::forward<U>(b));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading