check member function

4190 단어
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");

좋은 웹페이지 즐겨찾기