fork(1) download
  1. #include <iostream>
  2. #include <boost/utility/enable_if.hpp>
  3. #include <boost/static_assert.hpp>
  4.  
  5. // Has_hello<T>::value is true if T has a hello function.
  6. template<typename T>
  7. struct has_hello {
  8. typedef char yes[1];
  9. typedef char no [2];
  10. template <typename U> struct type_check;
  11. template <typename U> static yes &chk(type_check<char[sizeof(&U::hello)]> *);
  12. template <typename > static no &chk(...);
  13. static const bool value = sizeof(chk<T>(0)) == sizeof(yes);
  14. };
  15.  
  16. template<typename T>
  17. void doSomething(T const& t,
  18. typename boost::enable_if_c<has_hello<T>::value>::type* = 0
  19. ) {
  20. return t.hello();
  21. }
  22.  
  23. // Would need another doSomething` for types that don't have hello().
  24.  
  25. struct Foo {
  26. void hello() const {
  27. std::cout << "hello" << std::endl;
  28. }
  29. };
  30.  
  31. // This check is ok:
  32. BOOST_STATIC_ASSERT(has_hello<Foo>::value);
  33.  
  34. int main() {
  35. Foo foo;
  36. doSomething<Foo>(foo);
  37. }
  38.  
Success #stdin #stdout 0.01s 2680KB
stdin
Standard input is empty
stdout
hello