Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. #include <iostream>
  2. #include <typeinfo>
  3.  
  4. // Defined in C++17. Needed by all checks
  5. template <class... Ts>
  6. using void_t = void;
  7.  
  8. // For each different member you want to check for, you need something like this
  9. template <class T, class=void>
  10. struct has_foo_member : std::false_type{};
  11.  
  12. template <class T>
  13. struct has_foo_member<T, void_t<decltype(T::foo)>> : std::true_type{};
  14.  
  15. // Where you can use the aforementioned checks with enable_if
  16. template <class T, std::enable_if_t<has_foo_member<T>::value>* = nullptr>
  17. void print_has_foo_member() {
  18. std::cout << "Class " << typeid(T).name() << ": has a foo member" << std::endl;
  19. }
  20.  
  21. template <class T, std::enable_if_t<!has_foo_member<T>::value>* = nullptr>
  22. void print_has_foo_member() {
  23. std::cout << "Class " << typeid(T).name() << ": does not have a foo member" << std::endl;
  24. }
  25.  
  26. // Here are some example classes we will check
  27. struct Empty {
  28. };
  29.  
  30. struct HasStaticFoo {
  31. static int foo;
  32. };
  33.  
  34. struct HasNonstaticFoo {
  35. double foo;
  36. };
  37.  
  38. struct HasFooMethod {
  39. double foo(){ return 1; };
  40. };
  41. int main()
  42. {
  43. print_has_foo_member<Empty>();
  44. print_has_foo_member<HasStaticFoo>();
  45. print_has_foo_member<HasNonstaticFoo>();
  46. print_has_foo_member<HasFooMethod>();
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement