fork(4) download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. struct Foo {
  6. size_t length() { return 1; }
  7. };
  8.  
  9. struct Bar {
  10. void length();
  11. };
  12.  
  13. template <typename R, bool result = std::is_same<decltype(((R*)nullptr)->length()), size_t>::value>
  14. constexpr bool hasLengthHelper(int) {
  15. return result;
  16. }
  17.  
  18. template <typename R>
  19. constexpr bool hasLengthHelper(...) { return false; }
  20.  
  21. template <typename R>
  22. constexpr bool hasLength() {
  23. return hasLengthHelper<R>(0);
  24. }
  25.  
  26. template <typename R>
  27. typename std::enable_if<hasLength<R>(), size_t>::type lengthOf (R r) {
  28. return r.length();
  29. }
  30.  
  31. int main() {
  32. std::cout << hasLength<Foo>() << "; " << hasLength<std::vector<int>>() << "; " << hasLength<Bar>() << "\n";
  33. std::cout << lengthOf(Foo()) << std::endl;
  34. return 0;
  35. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
1; 0; 0
1