c – sfinae使用decltype检查静态成员

我写了下面的代码来尝试检测一个类型是否有一个静态成员变量.不幸的是,它总是返回,变量不存在.

有人可以告诉我我哪里错了吗?我使用的是g 4.7.1.

#include <iostream>
#include <utility>
#include <type_traits>

using namespace std;

template <class T>                                                  
class has_is_baz                                                          
{                                                                   
    template<class U,typename std::enable_if<std::is_same<bool,decltype(U::is_baz)>::value>::type...>                    
        static std::true_type check(int);                           
    template <class>                                                
        static std::false_type check(...);                          
public:                                                             
    static constexpr bool value = decltype(check<T>(0))::value;     
};

struct foo { };

struct bar 
{ 
    static constexpr bool is_baz = true;
};

int main()
{
    cout << has_is_baz<foo>::value << '\n';
    cout << has_is_baz<bar>::value << '\n';
}

解决方法

主要问题是:
std::is_same<bool,decltype(bar::is_baz)>::value == false

那么你的SFINAE总​​是失败.我重写了has_is_baz trait,现在它可以工作:

#include <iostream>
#include <utility>
#include <type_traits>

using namespace std;

template <class T>                                                  
class has_is_baz                                                          
{       
    template<class U,class = typename std::enable_if<!std::is_member_pointer<decltype(&U::is_baz)>::value>::type>
        static std::true_type check(int);
    template <class>
        static std::false_type check(...);
public:
    static constexpr bool value = decltype(check<T>(0))::value;
};

struct foo { };

struct bar 
{ 
    static constexpr bool is_baz = true;
};

struct not_static {
    bool is_baz;
};

int main()
{
    cout << has_is_baz<foo>::value << '\n';
    cout << has_is_baz<bar>::value << '\n';
    cout << has_is_baz<not_static>::value << '\n';
}

演示here.

编辑:我已经修改了类型特征.正如@litb所说,它正在检测静态成员以及非静态成员.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...