【问题标题】:Type indexed tuple类型索引元组
【发布时间】:2013-04-11 01:24:27
【问题描述】:

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

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

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

【问题讨论】:

  • 同一种类型被使用两次怎么办?
  • 这个类将专门用于每种类型只使用一个元素的用例。
  • 我以前做过——也许是 7 年前——当时在 boost 邮件列表中提到过它,但没有人看到这个实用程序,我也懒得详细解释。我使用了 Alexandrescu 的 Loki 库,所以有一种方法可以做到。如果您尝试遇到麻烦,那么您将有一个值得回答的正确问题;-P。不错的是,您可以提供按索引号、访问者模式等返回类型的工具。并且请注意 cppguy 的问题 - 您可以轻松地将值包装成不同的类型。

标签: c++ templates generics tuples


【解决方案1】:

使用可变参数模板实现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 中,则不会编译。

【讨论】:

  • 我从没想过递归继承来解决这个问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
  • 2013-05-05
  • 2011-12-28
  • 2016-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多