微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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所说,它正在检测静态成员以及非静态成员.

原文地址:https://www.jb51.cc/c/112996.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐