c++ - 带有模板参数的 make_tuple 不编译

标签 c++ c++11 tuples rvalue-reference

考虑这段代码:

#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
}

为什么 auto tup3 = ...不编译?显然,make_tuple<int>(...)想要一个右值引用作为它的参数;但是为什么?

(我使用的是 GCC 6.1.0。)

最佳答案

std::make_tuple std::make_pair旨在推断模板参数(除其他外,如解包引用包装器)。明确提供它们是错误的。

在这种特殊情况下,这是因为右值的模板推导产生了它们的类型,类似于这个例子:

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

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

这就是为什么 make_tuple<int>(...)想要对其参数的右值引用。

如果你想强制转换,你只需要说就是

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

关于c++ - 带有模板参数的 make_tuple 不编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40301919/

相关文章:

c++ - 奇怪的运算符重载, "operator T& () const noexcept { return *_ptr; }"

python - 类型错误 : <lambda>() missing 1 required positional argument: 'w'

python - 如何在 Python 中混合使用多个可选参数?

c++ - 如何从命令行捕获 exe 崩溃

c++ - 将类型转换结构指针转换为char指针引用

C++ wxWidgets - 没有宽度的 ScrolledWindow 的问题

c++ - 为什么无序容器不提供定义最小负载因子的接口(interface)?

c++ - 线程之间的 bool 停止信号

python - 如何从元组python列表中删除所有字符串

c++ - 需要一些帮助在 g++ 中编译 "Hello World"