How to check if a member name (variable or function) exists in a class, with or without specifying type?

后端 未结 3 1221
说谎
说谎 2020-12-03 23:08

This Q is an extension of:
Is it possible to write a C++ template to check for a function\'s existence?

Is there any utility which will help to find:

    <
3条回答
  •  半阙折子戏
    2020-12-03 23:55

    With std::experimental::is_detected and std::experimental::disjunction you could do this:

    //check for a type member named foo
    template 
    using foo_type_t = typename T::foo;
    
    //check for a non-type member named foo
    template 
    using foo_non_type_t = decltype(&T::foo);
    
    template 
    using has_foo = disjunction,
                                is_detected>;
    

    Then you would use has_foo::value in whatever you want.

    The above will work for more than just types and member functions, but you could easily constrain it by using traits like std::is_member_function_pointer and std::is_member_object_pointer if you like.

    To supply your optional argument, you could use the std::experimental::is_detected_exact helper.

    Live Demo


    Note that if you take the implementations of the above traits from the pages I linked, you can use this with C++14. A minor change to the disjunction code will let you use it in C++11.

提交回复
热议问题