Is there real static polymorphism in C++?

前端 未结 5 683
夕颜
夕颜 2021-02-05 15:55

Here is a simple code in C++:

#include 
#include 

template
void function()
{
   std::cout << typeid(T).n         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-02-05 16:06

    For c++ the term 'static polymorphism' is normally used for e.g. the CRTP type design patterns:

    template 
    class Base
    {
          void someFunc() {
              static_cast(this)->someOtherFunc();
          };
    };
    
    class ADerived : public Base
    {
        void someOtherFunc() { 
            // ... 
        }
    };
    

    It generally means that types and inheritance constraints are deduced and verified at compile/link time. The compiler will emit error messages if operations are missing or invalid on the specified types. In that sense it's not really polymorphism.

提交回复
热议问题