我有一个简单的 SFINAE 场景来区分标准容器,如 std::map
:
template <typename Container> struct HasKeyType : sfinae_test { // (C)
template <typename U> static Yes test(typename Container::key_type*); // (A)
template <typename U> static No test(...);
enum {value = (sizeof(test(null)) == sizeof(Yes))}; // (B)
};
与
struct sfinae_test {
typedef char Yes;
typedef long No;
static void* const null;
};
当我用 HasKeyType<std::vector<int> >::value
实例化它时, 我得到
(A) error: no type named ‘key_type’ in ‘class std::vector<int>’
(B) error: invalid use of incomplete type ‘struct HasKeyType<std::vector<int> >’
(C) error: declaration of ‘struct HasKeyType<std::vector<int> >’
我完全被这个难住了。为什么是HasKeyType
不完整,为什么 SFINAE 不起作用?
我收到与 (B)
类似的错误和 (C)
以及如果我实例化 HasKeyType<std::map<int,float> >
实际上有一个键类型(int
)。
g++ 版本:4.5.2(是的,我知道它很旧)
最佳答案
您没有使用模板 U
在你的test
方法:
template <typename Container> struct HasKeyType : sfinae_test { // C
template <typename U> static Yes test(typename U::key_type* ); // A
template <typename U> static No test(U*);
enum {value = (sizeof(test<Container>(0)) == sizeof(Yes))}; // B
};
请注意,我更改了 test(null)
对于 test<Container>(0)
.如果你的编译器支持它(好吧,gcc 4.5 不支持......),你可以使用 nullptr
而不是 0
.
关于c++ - 我的 SFINAE 检查 std::map/std::vector 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10871850/