为什么基于 int 的访问对 std::get(std::tuple) 不起作用?

Why doesn't the int-based access work for std::get(std::tuple)?

Visual Studio 2017 下划线 "std::get" 红色,因此程序无法编译。我该怎么做才能让它发挥作用?

片段:

std::tuple<int, int, int>t;
t = {1,1,1};
int a = 0;
int b = std::get<a>(t);

get 是一个模板,所以 a 必须在编译时知道,所以它应该是 constexpr.

constexpr int a = 0;

模板参数在编译时计算。您可以通过使用 constexpr 使编译器能够在编译时评估 a 的值来修复您的错误。

std::tuple<int, int, int> t;
t = {1, 1, 1};
constexpr int a = 0;
int b = std::get<a>(t);

或者,如果您的元组只包含一种类型的元素,您可以将其替换为 std::arraystd::vector(或任何类似的容器)并在 运行 处执行下标时间.

std::array<int, 3> array;
t = {1, 1, 1};
int a = 0;
int b = array[a];