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

后端 未结 6 1823
清酒与你
清酒与你 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:23

    Here's something I hacked up which may or may not be what you need; it does seem to give true (false) for (const) int &...

    #include 
    
    template 
    struct Callable
    {
    private:
      typedef char                      yes;
      typedef struct { char array[2]; } no;
    
      template 
      static yes test(decltype(std::declval()(std::declval())) *);
    
      template 
      static no test(...);
    
    public:
      static bool const value = sizeof(test(nullptr)) == sizeof(yes);
    };
    
    struct Foo
    {
      int operator()(int &) { return 1; }
      // int operator()(int const &) const { return 2; } // enable and compare
    };
    
    #include 
    int main()
    {
      std::cout << "Foo(const int &): " << Callable::value << std::endl
                << "Foo(int &):       " << Callable::value << std::endl
        ;
    }
    

提交回复
热议问题