How to detect the presence of a static member function with certain signature?

前端 未结 3 597
一生所求
一生所求 2020-12-18 11:08

I found several questions & answers on SO dealing with detecting at compile time (via SFINAE) whether a given class has a member of certain name, type, or signature. How

3条回答
  •  无人及你
    2020-12-18 11:31

    Simply invoke the member function and discard the result in a SFINAE context. If it succeeds, the method exists. If it fails, the method does not.

    // not needed in C++1y
    templateusing enable_if_t=typename enable_if::type;
    
    // If the other tests fail, the type T does not have a method `foo` of
    // signature Sig.  The class=void parameter is an implementation detail
    // that in an industrial quality implementation we would hide in a helper
    // template type.
    templatestruct has_foo:std::false_type{};
    
    // For R(Args...), we attempt to invoke `T::foo` with (Args...), then check
    // if we can assign the return value to a variable of type R.
    template
    struct has_foo()... ) ),
          R
        >::value
        && !std::is_same::value
      >
    >: std::true_type {};
    // for `void` return value, we only care if the function can be invoked,
    // no convertible test required:
    template
    struct has_foo()... ) ) )
    >: std::true_type {};
    

    use:

     has_foo< bar, int(int) >::value
    

    which checks if int r = T::foo( 7 ) is a valid expression, and not for exact signature match.

提交回复
热议问题