【问题标题】:Why is this traits class not working, to test if a class has a certain typedef?为什么这个特征类不起作用,以测试一个类是否具有特定的 typedef?
【发布时间】:2014-05-14 09:13:18
【问题描述】:

编辑:

好的,我想通了。当我应该使用bool 时,我使用false_typetrue_type 作为enable_if 的参数。 :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_typemapped_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 应该允许我根据 C::key_type 是否可访问来选择正确的 test 重载。

这是我的测试方式:首先,一个在is_map_like 上专门使用enable_if 的结构:

// 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 不是地图类型 T 不是地图类型

我做错了什么?为什么test(typename C::key_type*) 甚至不用于map,它确实有一个key_type?还是我使用decltype的问题?

还有额外的好处:有什么调试技术可以解决这个问题吗?我如何检查如何选择专业化,甚至在编译时获得关于扩展的验证?也许有 VS 特定的扩展或编译时调试工具?

【问题讨论】:

    标签: c++ visual-c++ sfinae typetraits enable-if


    【解决方案1】:

    SFINAE 结构中的值是一个类型。

    制作:

    static constexpr bool value = decltype(test<T>(0))::value;
    

    它会起作用的

    【讨论】:

      猜你喜欢
      • 2012-10-01
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      相关资源
      最近更新 更多