Is there real static polymorphism in C++?

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

    Wikipedia lists three types of polymorphism:

    • If a function denotes different and potentially heterogeneous implementations depending on a limited range of individually specified types and combinations, it is called ad hoc polymorphism. Ad hoc polymorphism is supported in many languages using function overloading.

    • If the code is written without mention of any specific type and thus can be used transparently with any number of new types, it is called parametric polymorphism. In the object-oriented programming community, this is often known as generics or generic programming. In the functional programming community, this is often simply called polymorphism.

    • Subtyping (or inclusion polymorphism) is a concept wherein a name may denote instances of many different classes as long as they are related by some common superclass. In object-oriented programming, this is often referred to simply as polymorphism.

    The first one refers to function overloading. The third type refers to late binding or runtime polymorphism, the kind you would see for example in inheritance. The second one is what we're interested in.

    Templates are a compile-time construct and type deduction is a process when the compiler automatically figures out the template arguments. This is where static polymorphism comes in.

    For example:

    template 
    auto func(const T& t, const U& u) -> decltype(t + u)
    {
       return (t + u);
    }
    

    This will work for any two types with compatible plus operators. There's no need to specify the template argument if the compiler can figure it out. It would be ad hoc polymorphism if you wrote function overloads that performed different behavior, for example string concatenation vs integer addition.

    However, in your example, you have instantiations for your functions that are distinct, function and function. Here's a quote:

    To be polymorphic, [a()] must be able to operate with values of at least two distinct types (e.g. int and double), finding and executing type-appropriate code.

    In that case, the instantiations are specific for the type in which they were instantiated, so there is no polymorphism involved.

提交回复
热议问题