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!

  • possible duplicate https://stackoverflow.com/questions/8194227/how-to-get-the-i-th-element-from-an-stdtuple-when-i-isnt-know-at-compile-time – unknown.prince Jul 14 '20 at 11:59
  • Are you sure that you want a tuple or perhaps a [`std::variant`](https://en.cppreference.com/w/cpp/utility/variant)? – Timo Jul 14 '20 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! – Klaus Jul 14 '20 at 12:50
  • A tuple that you can access with a variable is spelled `std::array`. – n. m. could be an AI Jul 16 '20 at 06:33

1 Answers1

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:

Stefan Scheller
  • 953
  • 1
  • 12
  • 22