Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++11: building a std::tuple from a template function

I have the following function:

template<class T>
T Check(int index);

How can I write a function, CheckTuple, which, given a tuple type, populates a tuple with calls to Check?

For example:

CheckTuple< std::tuple<int, float, std::string> >()

would return the following tuple:

std::make_tuple( Check<int>(1), Check<float>(2), Check<std::string>(3) )

The other questions I see involve unpacking a given tuple, not building one up this way.

like image 805
Taylor Avatar asked Jan 14 '15 05:01

Taylor


2 Answers

Implementing what you're looking for becomes pretty simple using C++14's integer_sequence. If you don't have that available, here's a C++11 implementation written by Jonathan Wakely.

template<typename Tuple, int... I>
Tuple CallCheck(std::integer_sequence<int, I...>)
{
    return std::make_tuple(Check<typename std::tuple_element<I, Tuple>::type>(I)...);
}

template<typename Tuple>
Tuple CheckTuple()
{
    return CallCheck<Tuple>(std::make_integer_sequence<int, std::tuple_size<Tuple>::value>());
}

// Use it as 
auto tup = CheckTuple<std::tuple<int, float, std::string>>();

Live demo

like image 117
Praetorian Avatar answered Nov 05 '22 09:11

Praetorian


Here is my working test implementation. (Perhaps someone has an idea of how to improve upon it in terms of conciseness. Can I get rid of TupleInfo somehow?)

#include <typeinfo>
#include <tuple>
#include <iostream>

template<class T>
T Check(int i) {
    std::cout << "getting a " << typeid(T).name() << " at position " << i << std::endl;
    return T();
}

template<typename Signature>
struct TupleInfo;

template<class T, class... Args>
struct TupleInfo< std::tuple<T, Args...> > {
    using Head = T;
    using Tail = std::tuple<Args...>;
};

template<int N, class Tuple>
struct TupleChecker {

    static Tuple CheckTuple() {
        auto t = std::make_tuple(Check<typename TupleInfo<Tuple>::Head>(N));
        return std::tuple_cat(t, TupleChecker<N+1, typename TupleInfo<Tuple>::Tail >::CheckTuple());
    }

};

template<int N>
struct TupleChecker<N, std::tuple<> > {

    static std::tuple<> CheckTuple() {
        return std::tuple<>();
    }

};

template<class Tuple>
Tuple CheckTuple() {
    return TupleChecker<1, Tuple>::CheckTuple();
}

int main() {

    std::tuple<> t0 = CheckTuple<std::tuple<> >();

    std::tuple<int> t1 = CheckTuple<std::tuple<int> >();

    std::tuple<int, float, std::string> t2 = CheckTuple<std::tuple<int, float, std::string> >();

    return 0;

}
like image 42
Taylor Avatar answered Nov 05 '22 10:11

Taylor