I wanted to detect if I have a member in a simple POD struct and after some searching and merging some methods I found on the web I've come up with this solution:
#include <iostream>
template<class...Fs>
struct funcs_t{};
template<class F0, class...Fs>
struct funcs_t<F0, Fs...>: F0, funcs_t<Fs...> {
funcs_t(F0 f0, Fs... fs):
F0(std::move(f0)), funcs_t<Fs...>(std::move(fs)...)
{}
using F0::operator();
using funcs_t<Fs...>::operator();
};
template<class F>
struct funcs_t<F>:F {
funcs_t(F f) : F(std::move(f)) {};
using F::operator();
};
template<class...Fs>
funcs_t<std::decay_t<Fs>...> funcs(Fs&&...fs) {
return {std::forward<Fs>(fs)...};
}
#define HAS_MEMBER(cls, memb)\
[](){\
auto with_memb = [](auto &&A, int x)\
-> decltype(typename std::remove_reference<decltype(A)>::type().memb, std::true_type())\
{\
return std::true_type();\
};\
auto with_no_memb = [](auto &&A, float x) -> std::false_type {\
return std::false_type();\
};\
auto has_memb = funcs(with_memb, with_no_memb);\
return has_memb(cls(), 1);\
}()
struct A {
int a;
int b;
};
int main(int argc, char const *argv[])
{
std::cout << HAS_MEMBER(A, b) << std::endl;
return 0;
}