sfinae check for static member using decltype

The issue in your code is that a constexpr object is implicitly const, which means that your test for same type should be:

std::is_same<const bool, decltype(U::is_baz)>::value

This is specified in the standard in §7.1.5 [dcl.constexpr]/9

A constexpr specifier used in an object declaration declares the object as const. [...]


The main problem was that:

std::is_same<bool, decltype(bar::is_baz)>::value == false

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

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

Tags:

C++

C++11