Check if class has function with signature

后端 未结 3 538
遇见更好的自我
遇见更好的自我 2020-12-21 17:31

There are other answers on this site using SFINAE but with non C++11 code, and there are others using C++11 code like decltypes to make this process easier. However, I am no

3条回答
  •  醉梦人生
    2020-12-21 18:13

    The best way I know of is checking if you can actually call the function and if it returns the type you expect. Here's an example of how to detect if a class C has a receive method which takes const Event& as a parameter and "returns" void. The detection does not care whether the method is implemented in the class C directly or in some base class that C derives from, neither does it care whether there are further defaulted parameters. Adapt as needed.

    template< typename C, typename Event, typename = void >
    struct has_receive
      : std::false_type
    {};
    
    template< typename C, typename Event >
    struct has_receive< C, Event, typename std::enable_if<
        std::is_same<
            decltype( std::declval().receive( std::declval() ) ),
            void
        >::value
    >::type >
      : std::true_type
    {};
    

提交回复
热议问题