提问者:小点点

使用带有变量get的Cpp元组


所以,我试图使用带有变量的std::get来搜索元组的某个位置。 但令我惊讶的是,我无法使用元组访问任何位置。 你们知道为什么和如何克服这个问题吗? 我需要大量的容器给我不同的类型。

我将把我的代码放在这里:

#include <iostream>
#include <tuple>



struct MyStruct
{
    std::tuple<int, float> t;
    int pos;
} myStruct;

int main()
{
    MyStruct* var = new MyStruct();
    var->t = std::make_tuple(1,2.33);
    var->pos = 1;
    
    std::get<1>(var->t); //this works
    std::get<var->pos>(var->t); //this doesn't work but i need to search "dynamically"
}

最好的问候!


共1个答案

匿名用户

模板是在编译时解析的,因此您不能使用直到运行时才知道其值的变量来使用get访问元组。 如果您正在使用C++17,则可以使用类似std::vector的内容(建议阅读:std::any:How,when和why)。

  • C++11在运行时不使用开关索引元组的方法
  • 按索引C++11
  • 访问元组元素

相关问题