sfinae使用decltype检查静态成员 [英] sfinae check for static member using decltype

查看:275
本文介绍了sfinae使用decltype检查静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've written the below code to try to detect if a type has a static member variable. Unfortunately, it's always returning that the variable does not exist.

有人可以告诉我我会出错吗?我使用的是g ++ 4.7.1。

Could someone tell me where I'm going wrong? I'm using 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,现在工作原理:

Then your SFINAE was failing always. I've re-written the has_is_baz trait and it now works:

#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';
}

演示这里

编辑:我已修正类型特征。如@litb所示,它检测静态成员以及非静态成员。

Edit: I've fixed the type trait. As @litb indicated, it was detecting static members as well as non-static members.

这篇关于sfinae使用decltype检查静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆