Make_tuple with template parameters does not compile

Consider this code:

#include <tuple>

int main()
{
    int i;
    long k;

    auto tup1 = std::make_tuple<long>(i);   // Compiles
    auto tup2 = std::make_tuple<int>(k);    // Compiles
    auto tup3 = std::make_tuple<int>(i);    // Does not compile
    auto tup4 = std::make_tuple<int>(i+0);  // Compiles
    auto tup5 = std::make_tuple(i);         // Compiles
}

Why auto tup3 = ...doesn't it compile? Apparently make_tuple<int>(...)requires a reference to rvalue as an argument; but why?

(I am using GCC 6.1.0.)

+4
source share
1 answer

std::make_tupleand std::make_pairare intended for outputting template parameters (among other things, for example, for unpacking reference wrappers). Giving them is clearly a mistake.

In this particular case, this is because the template output for rvalues ​​gives their type similar to this example:

template<typename T>
void foo(T&&);

foo(42); // foo<int>(int&&)
int i{};
foo(i); // foo<int&>(int&) // after reference collapsing

and therefore make_tuple<int>(...)wants an rvalue reference to its argument.

, , ,

auto tup1 = std::tuple<long>(i);
+7

Source: https://habr.com/ru/post/1659166/


All Articles