Search code examples
c++c++11tuplesvariadic-templatesfriend

friend get function that returns type which calculates recursively through variadic template


I'm trying to implement an std::tuple through variadic template with recursive inheritance and external get function. I works well as long as tuple has public inheritance and public value field. But i need to make them private and to accomplish it i need to write a friend "get" function in the tuple. But the problem is that returned type of "get" is calculated through other variadic template. So I don't know what to write as returned value of that friend function.

#include <iostream>
#include <type_traits>

template <typename... Ts>
class Tuple{};


template <typename T, typename... Ts>
class Tuple<T, Ts...> : public Tuple<Ts...>
{
//    template<size_t k, typename T1, typename... T1s>
//    friend typename tuple_element<k, tuple<T1, T1s...>>::type&
//    get(Tuple<T1, T1s...>& t);
public:
    T m_head;
};

template<size_t index, typename>
struct tuple_element;

template<typename T, typename... Ts>
struct tuple_element<0, Tuple<T, Ts...>>
{
    typedef T type;
};

template<size_t k, typename T, typename... Ts>
struct tuple_element<k, Tuple<T, Ts...>>
{
    typedef typename tuple_element<k-1, Tuple<Ts...>>::type type;
};

template<size_t k, typename... Ts>
typename std::enable_if<k==0,
    typename tuple_element<0, Tuple<Ts...>>::type&>::type
get(Tuple<Ts...>& t)
{
    return t.m_head;
}

template<size_t k, typename T, typename... Ts>
typename std::enable_if<k!=0,
    typename tuple_element<k, Tuple<T, Ts...>>::type&>::type
get(Tuple<T, Ts...>& t)
{
    Tuple<Ts...>& super = t;
    return get<k-1>(super);
}

int main(int argc, char* argv[])
{
    Tuple<int, int, std::string> t;
    get<2>(t) = "3.14";
    std::cout << get<2>(t) << std::endl;
}

Commented code was my attempt to write such function but it doesn't work.


Solution

  • Forward-declare tuple_element and then make friends from the two overloaded get functions:

    template <size_t index, typename>
    struct tuple_element;
    
    template <typename T, typename... Ts>
    class Tuple<T, Ts...> : Tuple<Ts...>
    {
        template <size_t k, typename... Us>
        friend typename std::enable_if<k==0, typename tuple_element<0, Tuple<Us...>>::type&>::type get(Tuple<Us...>& t);
    
        template <size_t k, typename U, typename... Us>
        friend typename std::enable_if<k!=0, typename tuple_element<k, Tuple<U, Us...>>::type&>::type get(Tuple<U, Us...>& t);
    
    private:
        T m_head;
    };
    

    DEMO