Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <typeinfo>
- // Defined in C++17. Needed by all checks
- template <class... Ts>
- using void_t = void;
- // For each different member you want to check for, you need something like this
- template <class T, class=void>
- struct has_foo_member : std::false_type{};
- template <class T>
- struct has_foo_member<T, void_t<decltype(T::foo)>> : std::true_type{};
- // Where you can use the aforementioned checks with enable_if
- template <class T, std::enable_if_t<has_foo_member<T>::value>* = nullptr>
- void print_has_foo_member() {
- std::cout << "Class " << typeid(T).name() << ": has a foo member" << std::endl;
- }
- template <class T, std::enable_if_t<!has_foo_member<T>::value>* = nullptr>
- void print_has_foo_member() {
- std::cout << "Class " << typeid(T).name() << ": does not have a foo member" << std::endl;
- }
- // Here are some example classes we will check
- struct Empty {
- };
- struct HasStaticFoo {
- static int foo;
- };
- struct HasNonstaticFoo {
- double foo;
- };
- struct HasFooMethod {
- double foo(){ return 1; };
- };
- int main()
- {
- print_has_foo_member<Empty>();
- print_has_foo_member<HasStaticFoo>();
- print_has_foo_member<HasNonstaticFoo>();
- print_has_foo_member<HasFooMethod>();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement