fork(1) download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <type_traits>
  4. #include <sstream>
  5.  
  6. template<typename T>
  7. struct has_size_method
  8. {
  9. private:
  10. typedef std::true_type yes;
  11. typedef std::false_type no;
  12.  
  13. template<typename C>
  14. static yes test(int (C::*f)() const){
  15. return yes{};
  16. }
  17.  
  18. template<typename C>
  19. static yes test(size_t (C::*f)() const){
  20. return yes{};
  21. }
  22.  
  23. template<typename C>
  24. static auto test(decltype(&C::size),void*) -> decltype(test(&C::size)){
  25. return test(&C::size);
  26. }
  27.  
  28. template<typename C>
  29. static no test(...){
  30. return no{};
  31. }
  32.  
  33. public:
  34.  
  35. static constexpr bool value = std::is_same<decltype(test<T>(0,0)),yes>::value;
  36. };
  37.  
  38. struct int_size{
  39. int size() const { return 42; };
  40. };
  41.  
  42. struct derived_int_size : int_size{};
  43.  
  44. struct size_t_size{
  45. std::size_t size() const { return 42; }
  46. };
  47.  
  48. struct derived_size_t_size : size_t_size{};
  49.  
  50. struct void_size{
  51. void size() {}
  52. };
  53.  
  54. struct no_size{};
  55.  
  56. struct template_int_size{
  57. template<typename=int>
  58. int size() const { return 42; }
  59. };
  60.  
  61. struct overloaded_size{
  62. size_t size() const { return 42; }
  63. int size() { return 41; }
  64. };
  65.  
  66. int main()
  67. {
  68. using namespace std;
  69. #define dbg(x) { stringstream s; s << boolalpha << left << setw(8) << has_size_method<x>::value << #x; cout << s.str() << endl; }
  70.  
  71. dbg(int_size);
  72. dbg(derived_int_size);
  73. dbg(size_t_size);
  74. dbg(derived_size_t_size);
  75. dbg(void_size);
  76. dbg(no_size);
  77. dbg(template_int_size);
  78. dbg(overloaded_size);
  79. }
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
true    int_size
true    derived_int_size
true    size_t_size
true    derived_size_t_size
false   void_size
false   no_size
false   template_int_size
false   overloaded_size