SFINAE - Trying to determine if template type has member function with 'variable' return type

点点圈 提交于 2019-12-04 07:32:07

Are you asking how to implement such a trait, or why decltype isn't behaving as you expect? If the former, here's one approach:

#include <type_traits>

template<typename T, bool DisableB = std::is_fundamental<T>::value>
struct HasOperatorMemberAccessor
{ 
private:
    typedef char no;
    struct yes { no m[2]; };

    struct ambiguator { char* operator ->() { return nullptr; } };
    struct combined : T, ambiguator { };
    static combined* make();

    template<typename U, U> struct check_impl;
    template<typename U>
    static no check(
        U*,
        check_impl<char* (ambiguator::*)(), &U::operator ->>* = nullptr
    );
    static yes check(...);

public:
    static bool const value=std::is_same<decltype(check(make())), yes>::value;
};

// false for fundamental types, else the definition of combined will fail
template<typename T>
struct HasOperatorMemberAccessor<T, true> : std::false_type { };

// true for non-void pointers
template<typename T>
struct HasOperatorMemberAccessor<T*, false> :
    std::integral_constant<
        bool,
        !std::is_same<typename std::remove_cv<T>::type, void>::value
    >
{ };

template<typename X>
struct PointerX
{
    X* operator ->() const { return nullptr; }
};

struct X { };

int main()
{
    static_assert(
        HasOperatorMemberAccessor<PointerX<bool>>::value,
        "PointerX<> has operator->"
    );
    static_assert(
        !HasOperatorMemberAccessor<X>::value,
        "X has no operator->"
    );
    static_assert(
        HasOperatorMemberAccessor<int*>::value,
        "int* is dereferencable"
    );
    static_assert(
        !HasOperatorMemberAccessor<int>::value,
        "int is not dereferencable"
    );
    static_assert(
        !HasOperatorMemberAccessor<void*>::value,
        "void* is not dereferencable"
    );
}

VC++ 2010 lacks the necessary C++11 facilities (e.g. expression SFINAE) needed to make this much cleaner.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!