Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use std::get in a tuple wrapper class?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>(); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading