1

I have an object that must store a tuple for some reason, something similar to this:

template<typename... Types>
class MultiStorer {
public:
    tuple<Types...> my_tuple;
    MultiStorer(Types... elem) : my_tuple(tuple<Types...>(elem...)) {};

    auto getElem(int&& pos) {
        return get<pos>(my_tuple);
    }


};

But i get this compiler error C2672: 'get': no matching overloaded function found.

I don`t get errors when I use 'get' over an instance of the object outside the class, just when I use 'get' inside of the class.

int main()
{

    MultiStorer multistorer{ int(2),int(3) };
    cout << get<0>(multistorer.my_tuple); // This works 
    cout << multistorer.getElem(0);       // This doesn't


    return 0;
}
StefanOx26
  • 13
  • 2
  • 1
    All types need to be resolved at compile time. The type of a `std::get` depends on the index. So the index must be a compile time constant, otherwise its type can't be resolved at compile time. This is why the index can't be a normal function argument, since those aren't required to be compile time constant but template arguments are. – François Andrieux Oct 25 '22 at 13:31
  • [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Evg Oct 25 '22 at 14:21

1 Answers1

3

A function parameter can never be used as a constant expression, so you cannot use it as the non type template parameter of get. What you can do is make your own function a template like

template <std::size_t pos>
auto getElem() {
    return get<pos>(my_tuple);
}

and then you would use it like

cout << multistorer.getElem<0>(); 
NathanOliver
  • 171,901
  • 28
  • 288
  • 402