Home > front end >  How to use std::get in a tuple wrapper class?
How to use std::get in a tuple wrapper class?

Time:10-26

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;
}

CodePudding user response:

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>(); 
  • Related