Guilherme Gil
Guilherme Gil

Reputation: 51

Cpp Tuple use get with a variable

So, i was trying to use std::get with a variable to search a certain position of a tuple. But for my surprise i cannot access any position using a tuple. Do you guys know why and how to overcome this problem? I need a lot of a container that gives me different types.

I will put my code here:

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

best regards!

Upvotes: 0

Views: 1286

Answers (1)

Stefan Scheller
Stefan Scheller

Reputation: 953

Templates are resolved at compile time, so you cannot use a variable whose value is not known until runtime to access the tuple with get. If you are using C++17 an alternative could be to use something like std::vector<std::any> (suggested reading: std::any: How, when, and why).

Related Questions:

Upvotes: 1

Related Questions