CRTP to avoid virtual member function overhead

前端 未结 4 1695
鱼传尺愫
鱼传尺愫 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:48

    However it seems that the derived class does not require a definition to compile as it inherits one (the code compiles fine without defining a my_type::foo).

    C++ is lazy : it will not try to make base::foo() if you do not actually use it. But if you try to use it, then it will be created and if that fails, compilation errors will flow. But in your case, base::foo() can be instanciated just fine :

    template 
    struct base {
      void foo() {
        static_cast(this)->foo();
      };
    };
    
    struct my_type : base {};
    
    void func() {
        my_type m;
        static_cast& >(m).foo();
    }
    

    will compile just fine. When the compiler is presented with static_cast(this)->foo(), it will try to find a foo() that is accessible in my_type. And there is one: it's called base::foo(), which is public from a publicly inherited class. so base::foo() calls base::foo(), and you get an infinite recursion.

提交回复
热议问题