1

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?

Maestro
  • 2,512
  • 9
  • 24
  • what other question did you read? When there are similar Q&As better explain in what way they do not answer your question, otherwise your question might get closed as a duplicate of something that looks like answering your question. – 463035818_is_not_an_ai Dec 01 '20 at 12:41
  • in any case we cannot clarify what you read unless you tell us what you read and what specifically you didn't understand – 463035818_is_not_an_ai Dec 01 '20 at 12:42
  • I've not understand why I need a version of `forward` to take just an l-value reference to type parameter and not a forwarding reference. – Maestro Dec 01 '20 at 12:42
  • Does this answer your question? https://stackoverflow.com/questions/3582001/what-are-the-main-purposes-of-using-stdforward-and-which-problems-it-solves One of the answers explains why two cases have to be considered – 463035818_is_not_an_ai Dec 01 '20 at 12:54

0 Answers0