CRTP to avoid virtual member function overhead

前端 未结 4 1720
鱼传尺愫
鱼传尺愫 2021-02-11 03:01

In CRTP to avoid dynamic polymorphism, the following solution is proposed to avoid the overhead of virtual member functions and impose a specific interface:

temp         


        
4条回答
  •  忘掉有多难
    2021-02-11 03:38

    No, imagine the following situation:

    template 
    void bar(base obj) {
       obj.foo();
    }
    
    base my_obj;
    bar(my_obj);
    

    Base's foo will be called instead of my_type's...

    Do this, and you will get your erro message:

    template 
    struct base {
      void foo() {
        sizeof(Derived::foo);
        static_cast(this)->foo();
      };
    };
    

    But I must confess I am not sure how this will work in compilers other than GCC, tested only with GCC.

提交回复
热议问题