Is there real static polymorphism in C++?

前端 未结 5 686
夕颜
夕颜 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:14

    While it can be argued that the example in the OP does not exhibit static polymorphism, the use of specialization can make a more compelling case:

    template
    class Base
    {
    public:
          int a() { return 7; }
    };
    
    template<>
    class Base
    {
    public:
          int a() { return 42; }
    };
    
    template<>
    class Base
    {
    public:
          int a() { return 121; }
    };
    

    We see here that for most classes a() will return 7; The specialized (derived) instanciations for int and double can have radically different behaviors, demonstrated in the simple case by the differing return values, the same can be done for templates with for example int parameters, and can exhibit what can be oddly termed as static recursive polymoprphism.

    While the term polymorphic is possibly being stretched, the concept is definately there. What is missing is not the ability to redefine functions, but the ability for specialized classes to automatically inherit functions that are not changing behavior.

提交回复
热议问题