3

如何实现一个按类型而不是按索引访问元素的元组类?类似于此界面的内容...

template<typename... T>
class Tuple
{
public:
    Tuple(T... elements);

    template<typename U>
    U &get();               // U is one of the types in T...
};
4

1 回答 1

2

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 中,则不会编译。

于 2013-04-11T03:57:35.597 回答