Is it possible to check if a member function is defined for a class even if the member is inherited from an unknown base class

前端 未结 3 632
小鲜肉
小鲜肉 2021-01-18 11:11

I found similar questions and answers like this one. However, as I tried out, this SFINAE tests only succeeded if the tested member is directly defined in the class being te

3条回答
  •  后悔当初
    2021-01-18 12:12

    In C++03, this is unfortunately not possible, sorry.

    In C++11, things get much easier thanks to the magic of decltype. decltype lets you write expressions to deduce the type of their result, so you can perfectly name a member of a base class. And if the method is template, then SFINAE applies to the decltype expression.

    #include 
    
    template 
    auto has_foo(T& t) -> decltype(t.foo(), bool()) { return true; }
    
    bool has_foo(...) { return false; }
    
    
    struct Base {
        void foo() {}
    };
    
    struct Derived1: Base {
        void foo() {}
    };
    
    struct Derived2: Base {
        using Base::foo;
    };
    
    struct Derived3: Base {
    };
    
    int main() {
        Base b; Derived1 d1; Derived2 d2; Derived3 d3;
    
        std::cout << has_foo(b) << " "
                  << has_foo(d1) << " "
                  << has_foo(d2) << " "
                  << has_foo(d3) << "\n";
    }
    

    Unfortunately ideone has a version of gcc that's too old for this and clang 3.0 is no better.

提交回复
热议问题