如何从元组中生成元组

How to make a tuple from a tuple?

本文关键字:元组      更新时间:2023-10-16

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

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) 如果是,我可以对变参数使用转换吗?

试试这个:

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, ""
    );
}

演示