Check if a class has a member function of a given signature

后端 未结 17 1490
無奈伤痛
無奈伤痛 2020-11-22 03:00

I\'m asking for a template trick to detect if a class has a specific member function of a given signature.

The problem is similar to the one cited here http://www.go

17条回答
  •  攒了一身酷
    2020-11-22 03:26

    You appear to want the detector idiom. The above answers are variations on this that work with C++11 or C++14.

    The std::experimental library has features which do essentially this. Reworking an example from above, it might be:

    #include 
    
    // serialized_method_t is a detector type for T.serialize(int) const
    template
    using serialized_method_t = decltype(std::declval.serialize(std::declval()));
    
    // has_serialize_t is std::true_type when T.serialize(int) exists,
    // and false otherwise.
    template
    using has_serialize_t = std::experimental::is_detected_t;
    
    

    If you can't use std::experimental, a rudimentary version can be made like this:

    template 
    using void_t = void;
    template