sfinae使用decltype检查静态成员

use*_*173 10 c++ c++11

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

有人能告诉我哪里出错了吗?我正在使用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';
}
Run Code Online (Sandbox Code Playgroud)

mfo*_*ini 10

主要问题是:

std::is_same<bool, decltype(bar::is_baz)>::value == false
Run Code Online (Sandbox Code Playgroud)

然后你的SFINAE总​​是失败.我重写了这个has_is_baz特性,它现在有效:

#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';
}
Run Code Online (Sandbox Code Playgroud)

在这里演示.

编辑:我修复了类型特征.正如@litb指出的那样,它正在检测静态成员以及非静态成员.


Dav*_*eas 5

代码中的问题是constexpr对象是隐式的const,这意味着您对同一类型的测试应该是:

std::is_same<const bool, decltype(U::is_baz)>::value
Run Code Online (Sandbox Code Playgroud)

这在§7.1.5[dcl.constexpr]/9中的标准中规定

对象声明中使用的constexpr说明符将对象声明为const.[...]