c++ - 为什么这个特征类不能工作来测试一个类是否具有特定的 typedef?

标签 c++ visual-c++ sfinae type-traits enable-if

编辑:

好吧,我明白了。我正在使用false_typetrue_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/

相关文章:

c++ - 设备未打开错误 + QIODevice::write

c++ - GDB 调试器问题 - 没有命名的源文件

c++ - 访问稍后在 C++ 中定义的类的成员

c++ - 有没有办法在 OnHotKey 函数中获取热键 ID?

c++ - 在模板函数返回类型上使用 std::enable_if 来利用 SFINAE - 编译错误

c++ - SFINAE 在评估模板参数中的 constexpr 时失败?

c++ - SQL Server 2005 和 2012 与 C++ 的兼容性

c++ - 将指向成员变量的指针作为参数时出错;为什么?

c# - 在获得 CPU 频率方面需要一些帮助

c++ - std::hash 特化使用 sfinae?