Search code examples
c++templatestuplesgeneric-programming

How would I implement a function to extract the elements of this class?


I was messing around with implementing tuples in C++ for fun and I got stuck with how I would, given the class below modify it so that I can easily by using templates extract each element by only using an index. Similar to std::get.

TL;DR: How would an implementation for extracting the elements inside the tuple look like?

template<typename first_t, typename ... arg_v>
class Tuple : public Tuple<arg_v ...>
{
public:

    Tuple()
    {
    }

    Tuple(const first_t&& A) :
        element(A)
    {
    }

    Tuple(const first_t& A, arg_v& ... args) :
        element(A), Tuple<arg_v ...>::Tuple(args ...)
    {
    }

    Tuple(const first_t&& A, arg_v&& ... args) :
        element(A), Tuple<arg_v ...>::Tuple(args ...)
    {
    }

    first_t element;
};

template<typename last_t>
class Tuple<last_t>
{
public:
    Tuple()
    {
    }

    Tuple(const last_t& A) :
        element(A)
    {
    }

    Tuple(const last_t&& A) :
        element(A)
    {
    }
    last_t element;
};

Solution

  • I used a recursive method. I know that pointers to void are evil, but we don't know which type will be returned, only who is using the code knows it; the cast to the type we want will be performed only by the last get.

    Keep in mind that this code will cast void*to what you want without any check.

    class Tuple : public Tuple<arg_v ...>
    {
        template<typename T>
        void get(int index, T& out)
        {
            out = *static_cast<T*>(get(index));
        }
    
        void* get(unsigned int index)
        {
            if (index == 0)
                return &element;
            else
                return Tuple<arg_v ...>::get(index - 1);
        }
    };
    class Tuple<last_t>
    {
        void* get(unsigned int)
        {
            return &element;
        }
    };