Calling a free function instead of a method if it doesn't exist

前端 未结 4 878
滥情空心
滥情空心 2021-02-01 07:33

Suppose you have a family of type-unrelated classes implementing a common concept by means of a given method returning a value:

class A { public: int val() const         


        
4条回答
  •  情书的邮戳
    2021-02-01 07:46

    Just a somewhat longer comment... Your question has been answered. But I recently had a similar problem. Say you want to write a method to print strings to cout: Use member function write(std::cout), if not available use free function to_string(), if not available fallback to operator<<. You can use expression SFINAE as in the answer and a little class hierarchy to disambiguate the overloads:

    struct S3 {};
    struct S2 : S3 {};
    struct S1 : S2 {};
    
    template 
    auto print(S1, T const& t) -> decltype(t.write(std::cout)) {
        t.write(std::cout);
    }
    
    template 
    auto print(S2, T const& t) -> decltype(std::cout << to_string(t)) {
        std::cout << to_string(t);
    }
    
    template 
    void print(S3, T const& t) {
        std::cout << t;
    }
    
    template 
    void print(T const& t) {
        print(S1(), t);
    }
    

提交回复
热议问题