类型索引元组

Type indexed tuple

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

如何实现按类型而不是按索引访问元素的元组类?

template<typename... T>
class Tuple
{
public:
    Tuple(T... elements);
    template<typename U>
    U &get();               // U is one of the types in T...
};

使用可变模板实现Tuple的方式是这样的

// Base case, Tuple<>
template< typename... Ts >
class Tuple {
};
// recursive inheritance :D
template< typename T, typename... Ts >
class Tuple< T, Ts... > : private Tuple< Ts... > {
public:
   // we implement get() by checking wether element type match with
   // request type
   template< typename t >
   typename std::enable_if< std::is_same< t, T >::value, t& >::type
   get() {
     return element;
   }
   // above is not enough since it only check this class's element type,
   // we can check the rest of the tuple by inspecting its the parent classes.
   template< typename t >
   typename std::enable_if< !( std::is_same< t, T >::value ), t& >::type
   get() {
       return Tuple<Ts...>::template get<t>();  // call its parent's get() 
                                                // ::template to shut compiler up
   }       
private:
    T element;
};

Tuple< short, int, float, double, char, std::string > t;
auto x = t.get< std::string >();    //  x will be an empty string.

假设没有重复的元素类型,如果有,它将选择最前面的那个。如果请求类型不是Tuple,它将无法编译。