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

后端 未结 17 1731
無奈伤痛
無奈伤痛 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:33

    I had a similar need and came across o this SO. There are many interesting/powerful solutions proposed here, though it is a bit long for just a specific need : detect if a class has member function with a precise signature. So I did some reading/testing and came up with my version that could be of interest. It detect :

    • static member function
    • non-static member function
    • non-static member function const

    with a precise signature. Since I don't need to capture any signature (that'd require a more complicated solution), this one suites to me. It basically used enable_if_t.

    struct Foo{ static int sum(int, const double&){return 0;} };
    struct Bar{ int calc(int, const double&) {return 1;} };
    struct BarConst{ int calc(int, const double&) const {return 1;} };
    
    // Note : second typename can be void or anything, as long as it is consistent with the result of enable_if_t
    template struct has_static_sum : std::false_type {};
    template
    struct has_static_sum::value,T> 
                          > : std::true_type {};
    
    template struct has_calc : std::false_type {};
    template
    struct has_calc ::value,T>
                    > : std::true_type {};
    
    template struct has_calc_const : std::false_type {};
    template
    struct has_calc_const ::value,T>
                          > : std::true_type {};
    
    int main ()
    {
        constexpr bool has_sum_val = has_static_sum::value;
        constexpr bool not_has_sum_val = !has_static_sum::value;
    
        constexpr bool has_calc_val = has_calc::value;
        constexpr bool not_has_calc_val = !has_calc::value;
    
        constexpr bool has_calc_const_val = has_calc_const::value;
        constexpr bool not_has_calc_const_val = !has_calc_const::value;
    
        std::cout<< "           has_sum_val " << has_sum_val            << std::endl
                 << "       not_has_sum_val " << not_has_sum_val        << std::endl
                 << "          has_calc_val " << has_calc_val           << std::endl
                 << "      not_has_calc_val " << not_has_calc_val       << std::endl
                 << "    has_calc_const_val " << has_calc_const_val     << std::endl
                 << "not_has_calc_const_val " << not_has_calc_const_val << std::endl;
    }
    

    Output :

               has_sum_val 1
           not_has_sum_val 1
              has_calc_val 1
          not_has_calc_val 1
        has_calc_const_val 1
    not_has_calc_const_val 1
    

提交回复
热议问题