Why I can't use a single version for std::forward that takes a forwarding reference like std::move?

74 Views Asked by At

I've read on std::forward which is a function template, its purpose is to preserve the details of its argument passing it (forwarding it) to another function. The details include const, reference...

It comes in handy when called from inside another function template that have some parameters as universal (forwarding) references to a type parameters.

So I've implemented my version this way:

#include <iostream>


template <typename T>
T&& forward_(T&& entity)
{
    return static_cast<T&&>(entity);
}


template <typename T>
T&& forward_(T& entity)
{
    return static_cast<T&&>(entity);
}


template <typename T, typename U, typename F>
void call_fcn(T&& x, U&& y, F func)
{
    func(forward_<T>(x), forward_<U>(y));
}

void swap_(int& x, int& y)
{
    using std::swap;
    swap(x, y);
}

void print(int&& a, int&& b)
{
    std::cout << a << '\t' << b << '\n';
}

int main()
{

    int a = 7, b = 5;
    std::cout << a << '\t' << b << '\n';
    call_fcn(a, b, swap_);
    std::cout << a << '\t' << b << '\n';

    call_fcn(1, 2, print);


    std::cout << "\nDone!\n";
}

The output:

    7   5
    5   7
    1   2
  • Why the second version is needed for r-values?

  • As I guess the first version is sufficient because after reference collapsing the right value is returned (l-value ref or r-value ref) which I guess there is no need for the second version.

  • Am I missing something in my implementation? I've seen something like std::eneble_if in forward but I am still learning step by step. Thank you!

  • The second version of forward_ doesn't take a forwarding reference? it takes an l-value reference to the template type parameter?

0

There are 0 best solutions below