Static duck typing in C++

后端 未结 5 2294
日久生厌
日久生厌 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:53

    Concerning questions 1 and 2: since C++14 you can omit explicit template boilerplate and use auto, but only in lambdas:

    auto let_them_quack = [] (auto & donald, auto & daisy){
        donald.quack();
        daisy.quack();
    };
    

    (yes, I prefer references to pointers). GCC allows to do so in usual functions as an extension.

    For the question 3, what you are talking about are called concepts. They existed in C++ for a long time, but only as a documentational term. Now the Concepts TS is in progress, allowing you to write something like

    template
    concept bool Quackable = requires(T a) {
        a.quack();
    };
    
    void let_them_quack (Quackable & donald, Quackable & daisy);
    

    Note that it is not yet C++, only a technical specification in progress. GCC 6.1 already seems to support it, though. Implementations of concepts and constraints using current C++ are possible; you can find one in boost.

提交回复
热议问题