加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 06:01:44 所属栏目:百科 来源:网络整理
导读:我写了下面的代码来尝试检测一个类型是否有一个静态成员变量.不幸的是,它总是返回,变量不存在. 有人可以告诉我我哪里错了吗?我使用的是g 4.7.1. #include iostream#include utility#include type_traitsusing namespace std;template class T class has_is_
我写了下面的代码来尝试检测一个类型是否有一个静态成员变量.不幸的是,它总是返回,变量不存在.

有人可以告诉我我哪里错了吗?我使用的是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所说,它正在检测静态成员以及非静态成员.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读