Static duck typing in C++

后端 未结 5 2293
日久生厌
日久生厌 2021-02-15 14:45

C++ has some sort of duck typing for types given by template parameters. We have no idea what type DUCK1 and DUCK2 will be, but as long as they can

5条回答
  •  长发绾君心
    2021-02-15 14:57

    You will be able to make it look preetier with concept (not yet in standard - but very close):

    http://melpon.org/wandbox/permlink/Vjy2U6BPbsTuSK3u

    #include 
    
    templateconcept bool ItQuacks(){
        return requires (T a) {
            { a.quack() } -> void;
        };
    }
    
    void let_them_quack2(ItQuacks* donald, ItQuacks* daisy){
      donald->quack();
      daisy->quack();
    }
    
    struct DisneyDuck {
        void quack(){ std::cout << "Quack!";}
    };
    
    struct RegularDuck {
        void quack(){ std::cout << "Quack2!";}
    };
    
    struct Wolf {
        void woof(){ std::cout << "Woof!";}
    };
    
    int main() {
        DisneyDuck q1, q2;
        let_them_quack2(&q1, &q2);
    
        RegularDuck q3, q4;
        let_them_quack2(&q3, &q4);    
    
        //Wolf w1, w2;
        //let_them_quack2(&w1, &w2);    // ERROR: constraints not satisfied
    }
    

    output:

     Quack!Quack!Quack2!Quack2!
    

    As you can see, you will be able to: omit writing a template parameter list, ItQuacks is quite explicit so types are never used and that it's only the interface that matters takes place. This I'd like to have sort of an interface annotation/check. also takes place, concept use will also give you meaningfull error message.

提交回复
热议问题