fork(16) download
  1. #include <iostream>
  2.  
  3. template <typename T>
  4. class has_size {
  5. private:
  6. typedef char Yes;
  7. typedef Yes No[2];
  8.  
  9. template<typename C> static auto Test(void*)
  10. -> decltype(size_t{std::declval<C const>().size()}, Yes{});
  11.  
  12. template<typename> static No& Test(...);
  13.  
  14. public:
  15. static bool const value = sizeof(Test<T>(0)) == sizeof(Yes);
  16. };
  17.  
  18. struct NoSize {};
  19.  
  20. struct Sized { size_t size() const { return 0; } };
  21.  
  22. struct BadlySized { int size() { return 0; } };
  23.  
  24. struct MultiSized { size_t size() const { return 0; } int size(int) { return 0; } };
  25.  
  26. int main() {
  27. std::cout << "NoSize: " << has_size<NoSize>::value << "\n";
  28. std::cout << "Sized: " << has_size<Sized>::value << "\n";
  29. std::cout << "BadlySized: " << has_size<BadlySized>::value << "\n";
  30. std::cout << "MultiSized: " << has_size<MultiSized>::value << "\n";
  31. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
NoSize: 0
Sized: 1
BadlySized: 0
MultiSized: 1