2
void f(const std::vector<int>& v)  //#1
{
    std::vector<int> a(v);
    ...
}
void f(std::vector<int>&& v)       //#2
{
    std::vector<int> a(std::move(v));
    ...
}

Is there some way to write #1 and #2 in one function without overloading but achieving the same effect? I mean, if argument is lvalue, then use copy constructor, if argument is rvalue, then use move constructor.

As you can see, if there is more than one parameter, I will need to write 2^n overloads.

crupest
  • 124
  • 1
  • 1
  • 10
  • 1
    If both overloads do the same thing, drop the second one. If they don't, you can use some template magic but that is really unnecessary, and in some cases doesn't work (constructors, assignment operators for example). – Rakete1111 Oct 02 '17 at 16:01
  • I mean, you can pass the `A` by value instead, which will have basically the same effect as #2 (the value would be move-constructed) but would perform an unnecessary copy in the case of #1. – cdhowie Oct 02 '17 at 16:01
  • something like that for template magic: `template std::enable_it_t>::value> f(T&&);` – Jarod42 Oct 02 '17 at 16:04
  • @Jarod42 you're over-constraining the function. Put `std::is_base_of>` – Guillaume Racicot Oct 02 '17 at 16:05
  • Thank you all for response. I have edited the question and made it clearer. – crupest Oct 02 '17 at 16:12
  • 1
    afaik, http://en.cppreference.com/w/cpp/utility/forward could be the answer – johan d Oct 02 '17 at 16:18
  • 1
    If you are making a copy anyway, just pass by value. – T.C. Oct 02 '17 at 20:08

1 Answers1

-1

You don't need both! Using forwarding you could just as easily write:

template < typename T >
void f(T&& t)
{
  std::vector<int> v(std::forward<T>(t));
}

And then all these following calls would work:

std::vector<int> a = { 1, 2, 3 };
f(std::move(a));
f(a);

const std::vector<int> b = { 1, 2, 3 };
f(b);
Daniel Trugman
  • 8,186
  • 20
  • 41