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!

>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));
}

Leave a Reply