0

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!

4
  • possible duplicate stackoverflow.com/questions/8194227/… Commented Jul 14, 2020 at 11:59
  • Are you sure that you want a tuple or perhaps a std::variant? Commented Jul 14, 2020 at 12:19
  • 1
    What can you do if you you can get a specific element from a tuple which has different type? Can you show any real world use case please! Commented Jul 14, 2020 at 12:50
  • A tuple that you can access with a variable is spelled std::array. Commented Jul 16, 2020 at 6:33

1 Answer 1

1

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:

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.