C++ 容器内容特征混淆
c++ container contents traits confusion
我希望能够根据容器类的内容类型在编译时选择要实例化的不同类。Clang和GCC都为下面的代码提供了错误,所以我希望它有问题,即使它使用Visual Studio可以正确运行。有什么想法吗?
#include <iostream>
template <bool, class T = void>
struct enable_if {};
template <class T>
struct enable_if<true, T> {
typedef T type;
};
struct a {};
struct b {};
struct a_container {
typedef a contents_type;
};
struct b_container {
typedef b contents_type;
};
template <class T>
struct is_an_a { enum { value = false }; };
template <>
struct is_an_a<a> { enum { value = true }; };
template <class container_type>
struct container_traits {
typedef typename container_type::contents_type value_type;
};
template <class container_type>
struct is_an_a_container {
enum { value = typename is_an_a<typename container_traits<container_type>::value_type>::value };
};
template<class container_type, class enable = void>
struct S {
void operator()() {
std::cout << "Not an An";
}
};
template<class container_type>
struct S<container_type, typename enable_if<is_an_a_container<container_type>::value>::type> {
void operator()() {
std::cout << "Got an An";
}
};
int main() {
S<a_container>()();
S<b_container>()();
return 0;
}
在 Visual Studio 中,输出为:
Got an A
Not an A
GCC 失败,并显示:
35: error: expected `(' before '}' token
虽然Clang失败了:
35 : error: expected '(' for function-style cast or type construction
我可以通过将is_an_a_container
的定义内联到S
的第二个版本(例如下面)来解决这个问题,但在我看来它有点模糊,我想了解错误。
template<class container_type>
struct S<container_type, typename enable_if<is_an_a<typename container_traits<container_type>::value_type>::value>::type> {
void operator()() {
std::cout << "Got an An";
}
};
或者也许有一个更简洁的解决方案来实现目标?注意:我必须使用container_traits
。
template <class container_type>
struct is_an_a_container {
enum { value = typename is_an_a<typename conntainer_traits<container_type>::value_type>::value };
^^^^^^^^ ^^^^^ // this is not a type
};
只需删除类型名称
template <class container_type>
struct is_an_a_container {
enum { value = is_an_a<typename conntainer_traits<container_type>::value_type>::value };
};
相关文章:
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 特征命名访问向量段
- 将特征矩阵的向量设置为0
- 特征:模板函数中矩阵的平面图
- basic_string的前导/尾部不区分空格的特征
- 特征 3 类的模板专用化
- 特征 c++:复矩阵的面积双曲正切(atanh)
- C++ 中的特征向量计算
- 根据C++标准的定义实现"is_similar"类型特征
- C++类型特征,以查看是否可以<uint32_t>对类型"K"的任何变量调用"static_cast(k)"
- 有没有办法找到特征矩阵系数的中值?
- 如何将高维数据映射到特征类型?
- 将平面阵列重塑为复杂的特征类型
- 特征 LLT 模块给出不正确的结果?
- 特征模板化函数和维度
- 特征稀疏向量:求最大系数
- 特征 3.3.x:如何在所有行中操作 lamba?
- 如何将向量断言到特征矩阵