类型索引元组
Type indexed tuple
如何实现按类型而不是按索引访问元素的元组类?
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,它将无法编译。
相关文章:
- 重载元组索引运算符-C++
- 元组的运行时索引
- 为什么我在循环提升时得到意外的索引::hana::元组
- 在 Hana 中满足谓词的元组元素的索引序列
- 打包元组及其索引范围
- C++向量元组,请按索引从元素创建元组
- 为元组实现创建索引序列
- socket.io client std :: bind-错误C2338:元组索引限制
- 如何创建一个 std::tuple,其中包含由索引元组指定的向量中的成员
- 该模板如何工作以找到元组的索引
- 使用boost::引用元组作为orderedunique索引的关键字时出现boost多索引插入错误
- C++11 在运行时不使用 switch 为元组编制索引的方法
- 在运行时获取元组中索引的类型
- 通过索引 C++11 访问元组元素
- 用C++14索引序列可以改进元组变元模板递归吗
- 获取元组元素类型的索引?
- 如何通过地址获取元组中元素的索引
- 在c++中,当元组的元素索引在运行时已知时,是否有可能获得该元素的类型?
- 从元表字段/方法访问数组索引
- 类型索引元组