Search code examples
c++autodecltypeperfect-forwarding

C++ decltype with auto parameters to forward


Just posting here to see if anyone can lend some helpful information in a more ‘laymans’ explanation.

I’ve seen a lot here on stackoverflow regarding the difference between decltype and auto. However, I either didn’t click through enough forum posts, or it’s simply not there. This was a test question last week, which I couldn’t figure out for the life of me then, and I’m still super fuzzy on the details now after spending some quality time with Google and other various forums.

Why is one supposed to use decltype with auto&& parameters to std::forward them?

What does the pseudo/example code look like for this?

If you know of a similar post here, I’ll happily take the point in the right direction :)

I appreciate your help, thank you!


Solution

  • given the lambda function

    auto f = [](auto&& arg) {
      // ...
    };
    

    this is roughly equivalent to the template function:

    template<class Arg>
    auto f(Arg&& arg)
    {
      // ...
    }
    

    Note that in them template function we have the template type Arg which we can use to forward the argument arg

    so we could write

    do_something(std::forward<Arg>(arg));
    

    It just so happens that the decltype(arg) is Arg.

    so we can substitute:

    do_something(std::forward<decltype(arg)>(arg));
    

    In the lambda we don't have the template type Arg, but the decltype(arg) is equivalent.

    So again, the same expression serves our our purpose:

    auto f = [](auto&& arg) {
      do_something(std::forward<decltype(arg)>(arg));
    };
    

    or we can be a little kinder to the reader:

    auto f = [](auto&& arg) 
    {
      using arg_type = decltype(arg);
      do_something(std::forward<arg_type>(arg));
    };