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

标签 c++ visual-studio-2017

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

一个片段:

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

最佳答案

模板参数在编译时计算。您可以使用 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];

关于c++ - 为什么基于 int 的访问对 std::get(std::tuple) 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58921113/

相关文章:

c++ - 用 "layers"填充

Python C++ 扩展编译器警告

c# - VS2017 MSBuildWorkspace fails opening with converted ASP.Net Core Web application 解决方案

C# 交互式窗口不会引用我的代码

c++ - 强制调用基类虚函数

c++ - 从原始内存位置 memcpy 到 vector<wchar_t>

c++ - 为什么编译器在编译时不知道局部变量的地址?

c++ - 格式化输出以显示在错误列表的消息部分

asp.net-web-api - 找不到方法 : 'System.Net.Http.HttpRequestMessage System.Web.Http.Controllers.HttpActionContext.get_Request()'

msbuild - Bin/MSBuild.exe 和 Bin/amd64/MSBuild.exe 有什么区别