Static polymorphism in C++

后端 未结 2 2152
忘掉有多难
忘掉有多难 2021-02-20 08:01
#include 

template
struct renderer{
    void get(){
        static_cast(this)->get();
    }
};
struct open_gl : pub         


        
相关标签:
2条回答
  • 2021-02-20 08:46
    1. Becuase get is not marked const.
    2. Because the base class method is used (irrelevantly of cast), and it goes into infinite loop.
    0 讨论(0)
  • 2021-02-20 09:03

    1) Because get is not a const member function : it cannot make the promise of not modify your (const) argument.

    You could declare get as const, and it compiles fine :

    void get() const { ... }
    

    2) The base get method will be called, going into infinite recursion : Stack Overflow.

    If you declare your function override (it needs to be virtual), the compiler will throw an error if it does not indeed override a base method :

    void get1() override  { ... } // Compiler error
    void get() override   { ... } // Ok
    

    Note:

    The title is "Static polymorphism in C++", but I think that you misunderstood what is static polymorphism : it does not (have to) make use of inheritance (as you did). Rather, the templates compile-time duck typing will statically "resolve" function calls for you.

    That is, you don't need related types, you don't need the base renderer class at all, and you can simply do the following (in which case, renaming to get1 will cause a compiler error) :

    #include <iostream>
    
    struct open_gl {
        void get(){
            std::cout << "OpenGL" << std::endl;
        }
    };
    struct direct_draw {
        void get(){
            std::cout << "DX" << std::endl;
        }
    };
    
    template<typename T>
    void print_renderer(T r){
        r.get();
    }
    
    int main() {
        auto gl = open_gl();
        auto dx = direct_draw();
        print_renderer(gl);
        print_renderer(dx);
    }
    

    Live demo

    0 讨论(0)
提交回复
热议问题