如何从元组中创建元组?

时间:2013-07-12 15:52:26

标签: c++ templates tuples

例如,我有一个转换模板(任何现有的库都可以吗?)

template<class T> struct Convert;
template<> struct Convert<T0> {typedef C0 Type;};
template<> struct Convert<T1> {typedef C1 Type;};
template<> struct Convert<T2> {typedef C2 Type;};

从转换中,转换

std::tuple<T0, T1, T2>; // version A

std::tuple<C0, C1, C2>; // version B

通常的任何方式,例如

template<class tupleA, template<class> class Convert>
{
    typedef .... tupleB;
}

其他一些问题: (1)我可以从特定元组中获取其可变参数吗? (2)如果是这样,我可以在可变参数上使用convert吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

template <typename... Args>
struct convert;

template <typename... Args>
struct convert<std::tuple<Args...>>
{
    typedef std::tuple<typename Convert<Args>::Type...> type;
};

以下是一个示例程序:

#include <type_traits>
#include <tuple>

template<class T> struct Convert;
template<> struct Convert<int>  {typedef bool Type;};
template<> struct Convert<char> {typedef int Type;};
template<> struct Convert<bool> {typedef char Type;};

template <typename... Args>
struct convert;

template <typename... Args>
struct convert<std::tuple<Args...>>
{
    typedef std::tuple<typename Convert<Args>::Type...> type;
};

int main()
{
     static_assert(
        std::is_same<
            convert<std::tuple<int, char, bool>>::type,
            std::tuple<bool, int, char>
        >::value, ""
    );
}

Demo