Static duck typing in C++

后端 未结 5 2282
日久生厌
日久生厌 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 15:14

    #2 and #3 are sort of taken care of by the fact that the code will not compile, and throw a compilation error, if the given classes don't implement the interface. You could also make this formal:

    class duck {
    
    public:
       virtual void quack()=0;
    };
    

    Then declare the parameters to the function as taking a pointer to a duck. Your classes will have to inherit from this class, making the requirements for let_them_quack() crystal clear.

    As far as #1 goes, variadic templates can take care of this.

    void let_them_quack()
    {
    }
    
    template 
    void let_them_quack(duck* first_duck, Args && ...args) {
      first_duck->quack();
      let_them_quack(std::forward(args)...);
    }
    

提交回复
热议问题