Skip to content

Instantly share code, notes, and snippets.

@Mr-Slippery
Created March 5, 2020 17:41
Show Gist options
  • Save Mr-Slippery/641182cc745ddaf882a4f70abb784a12 to your computer and use it in GitHub Desktop.
Save Mr-Slippery/641182cc745ddaf882a4f70abb784a12 to your computer and use it in GitHub Desktop.
Basic data member detection in C++17
#include <type_traits>
#define HAS_MEMBER(member) \
template <typename T, typename = void> \
struct has_##member : std::false_type {}; \
template <typename T> \
struct has_##member<T, std::void_t<decltype(std::declval<T>().member)>> : std::true_type {};
struct WithBla {
int bla;
};
struct NoBla {
};
HAS_MEMBER(bla)
#include <iostream>
struct MyStruct {
template<typename A, std::enable_if_t<has_bla<A>::value, int> = 0>
MyStruct(A& par) {
std::cout << "To bla: " << par.bla << '\n';
}
template<typename A, std::enable_if_t<!has_bla<A>::value, int> = 0>
MyStruct(A& par) {
std::cout << "or not to bla?" << '\n';
}
};
int main(int argc, char *argv[])
{
WithBla wb{42};
NoBla nb;
MyStruct a(wb);
MyStruct b(nb);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment