【问题标题】:Cpp Tuple use get with a variableCpp 元组使用 get 与变量
【发布时间】:2020-07-14 11:46:44
【问题描述】:

所以,我试图使用带有变量的 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"
}

最好的问候!

【问题讨论】:

  • 您确定要一个元组还是 std::variant
  • 如果你可以从不同类型的元组中获取特定元素,你能做什么?你能展示任何真实世界的用例吗!
  • 可以通过变量访问的元组拼写为std::array

标签: c++ tuples containers


【解决方案1】:

模板是在编译时解析的,所以你不能使用一个直到运行时才知道值的变量来访问带有get的元组。如果您使用C++17,则可以使用std::vector&lt;std::any&gt; 之类的替代方法(建议阅读:std::any: How, when, and why)。

相关问题:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-17
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多