How do I determine if a type is callable with only const references?

后端 未结 6 1824
清酒与你
清酒与你 2021-02-04 13:08

I want to write a C++ metafunction is_callable that defines value to be true, if and only if the type F has the function cal

6条回答
  •  旧巷少年郎
    2021-02-04 13:39

    Here is a possible solution that utilizes an extra test to see if your template is being instantiated with a const T&:

    #include 
    #include 
    
    using namespace std;
    
    template
    struct is_callable {
    private:
    
      template
      static char (&test(...))[2];
    
      template
      struct helper {};
    
      template
      struct helper {
        typedef void *type;
      };
    
      template
      struct is_const_ref {};
    
      template
      struct is_const_ref {
        static const bool value = false;
      };
    
      template
      struct is_const_ref {
        static const bool value = true;
      };
    
      template
      static char test(typename helper::value, 
                                       sizeof(std::declval()(std::declval()), 0)>::type);
    public:
      static const bool value = (sizeof(test(0)) == sizeof(char));
    };
    
    struct foo {
      void operator()(const int &) {}
    };
    
    int main(void)
    {
      cout << is_callable::value << "\n";
      cout << is_callable::value << "\n";
    
      return 0;
    }
    

提交回复
热议问题