Is there real static polymorphism in C++?

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

Here is a simple code in C++:

#include 
#include 

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


        
5条回答
  •  梦毁少年i
    2021-02-05 16:32

    There is no static polymorphism in your example because there is no polymorphism. This is because function() does not look the same as function().

    Examples of static polymorphism would include simple function overloading, function templates that can work with type deduction, type traits, and the curiously recurring template pattern (CRTP). So this variation on your example would qualify as static polymorphism:

    #include 
    #include 
    
    template
    void function(T)
    {
       std::cout << typeid(T).name() << std::endl;
    }
    
    int main()
    {
       function(0);   // T is int
       function(0.0); // T is double
       return 0;
    }
    

    Here is another example:

    template
    void function(T t)
    {
      t.foo();
    }
    
    struct Foo() 
    {
      void foo() const {}
    };
    
    struct Bar() 
    {
      void foo() const {}
    };
    
    int main()
    {
      Foo f;
      Bar b;
      function(f); // T is Foo
      function(b); // T is Bar
    }
    

提交回复
热议问题