编辑:
好吧,我明白了。我正在使用false_type
和true_type
作为 enable_if
的参数当我应该使用bool
时。 :x
此外,我决定 is_map_like
类最好检查 value_type
就像,std::pair<const Tkey, Tmapped>
。所以,我的新特征类如下所示:
template<class Tcontainer>
struct is_map_like
{
private:
template<class TvalueType>
struct test
{
static const bool bvalue = false;
};
template<class TkeyType, class TmappedType>
struct test<std::pair<const TkeyType, TmappedType>>
{
static const bool bvalue = true;
};
public:
static const bool bvalue = test<typename Tcontainer::value_type>::bvalue;
};
我想创建一个is_map_like
检查 key_type
的类型特征类和mapped_type
。我很难构建这个。现在我只想检查 key_type
。到目前为止我有以下内容:
template<class T>
struct is_map_like
{
private:
template<typename C> static std::true_type test(typename C::key_type*);
template<typename C> static std::false_type test(...);
public:
typedef decltype(test<T>(0)) value;
};
value
这里似乎总是返回 false_type
。据我了解,SFINAE应该让我选择正确的test
过载基于是否C::key_type
可以访问。
以下是我的测试方式:首先,一个专门使用 enable_if
的结构体上is_map_like
:
// a class that will be specialized only for map-like types
template<class T, class Enable = void>
struct MyStruct
{
static void fn() { DebugLog(L"T is not a map type"); }
};
template<class T>
struct MyStruct<T, typename std::enable_if<is_map_like<T>::value>::type>
{
static void fn() { DebugLog(L"T is INDEED a map type"); }
};
这是我在运行时的调用方式:
void test_is_map()
{
MyStruct<std::vector<int>>::fn();
MyStruct<std::map<int, int>>::fn();
}
输出:
T is not a map type T is not a map type
我做错了什么?为什么是test(typename C::key_type*)
甚至不用于 map
,其中确实有 key_type
?或者是我使用 decltype
的问题?
还有额外的好处:是否有任何调试技术?我如何检查特化的选择方式,甚至在编译时获得有关扩展的验证?也许有 VS 特定的扩展或编译时调试工具?
最佳答案
SFINAE 结构中的值是一种类型。
做到:
static constexpr bool value = decltype(test<T>(0))::value;
它会起作用
关于c++ - 为什么这个特征类不能工作来测试一个类是否具有特定的 typedef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23650310/