How can I check whether a member function has const overload?

前端 未结 5 789
北海茫月
北海茫月 2021-01-19 05:30

Lets say I have

struct foo {
    void ham() {}
    void ham() const {}
};

struct bar {
    void ham() {}
};

Assuming I have a templated fu

5条回答
  •  醉酒成梦
    2021-01-19 05:39

    Another option is to simulate void_t(to appear officially in C++17), which makes use of expression SFINAE to make sure your function is call-able on a const instance, regardless of its return type.

    #include 
    #include 
    
    struct Foo
    {
        void ham() const;
        void ham();
    };
    
    struct Bar {
        void ham() {}
    };
    
    template
    using void_t = void;
    
    template
    struct has_const_ham: std::false_type{};
    
    template // specialization, instantiated when there is ham() const
    struct has_const_ham().ham())>> : 
        std::true_type{};
    
    int main()
    {
        std::cout << std::boolalpha;
        std::cout << has_const_ham::value << std::endl;
        std::cout << has_const_ham::value << std::endl;
    }
    

    EDIT

    If you want to enforce the return type, then derive the specialization from std::is_same, like

    template // specialization, instantiated when there is ham() const
    struct has_const_ham().ham())>> : 
        std::is_same().ham()), void> // return must be void
    {}; 
    

    Live on Coliru

提交回复
热议问题