check member function

template<typename T>
struct has_member_foo11
{
private:
    template<typename U> static auto check(int) -> decltype(std::declval<U>().foo(), std::true_type());

    template<typename U> static std::false_type check(...);
public:
    enum { value = std::is_same<decltype(check<T>(0)), std::true_type>::value };
};

//more universal

template<typename T, typename... Args>
struct has_member_foo11
{
private:
    template<typename U> static auto check(int) -> decltype(std::declval<U>().foo(std::declval<Args>()...), std::true_type());

    template<typename U> static std::false_type check(...);
public:
    enum { value = std::is_same<decltype(check<T>(0)), std::true_type>::value };
};

//Improve
#define HAS_MEMBER(member)\
template<typename T, typename... Args>struct has_member_##member\
{\
    private:\
        template<typename U> static auto Check(int) -> decltype(std::declval<U>().member(std::declval<Args>()...), std::true_type());\
        template<typename U> static std::false_type Check(...);\
    public:\
        enum{value = std::is_same<decltype(Check<T>(0)), std::true_type>::value};\
};

//test code
HAS_MEMBER(foo)
HAS_MEMBER(func)

struct MyStruct
{
    string foo() { return ""; }
    int func(int i) { return i; }
};

static_assert(has_member_foo<MyStruct>::value, "true");
static_assert(has_member_func<MyStruct, int>::value, "true");

 

posted on 2015-11-02 13:58  qicosmos(江南)  阅读(1386)  评论(0编辑  收藏  举报

导航