When it comes to one of the object-oriented features “ polymorphic ”, At my level, I can't say much new . Believe a lot of programmer code K More , All the dreams are “ In polymorphism ” running . The conventional polymorphism is C++ A feature of semantic built-in support , This feature can be achieved through virtual functions , In order to make a difference , Let's call this polymorphism “ Dynamic polymorphism ” or ” Operation period polymorphism “, But this article always wants to discuss “ Static polymorphism ”, It can also be called “ Compile time polymorphism ”, At the same time, let's take a look at , What surprises will static polymorphism bring us , Wait and see .

First of all, let's look at a normal example of realizing polymorphism through virtual functions , As shown below , It's simple and clear. There's no need to say more .

 
#include <iostream>
#include <string> class BasicClassic
{
public:
virtual void Print() = 0;
}; class DerivedClassic1 : public BasicClassic
{
public:
DerivedClassic1() {} virtual void Print() {
std::cout << "DerivedClassic1 Print" << std::endl;
}
}; class DerivedClassic2 : public BasicClassic
{
public:
DerivedClassic2() {} virtual void Print() {
std::cout << "DerivedClassic2 Print" << std::endl;
}
};
Through virtual functions , At run time through the virtual function table pointer , Find the corresponding function through the index , And then call , So we call it dynamic polymorphism or runtime polymorphism . What about static polymorphism , How to achieve it ? The answer is the template . If you are familiar with COM You should have seen many polymorphic implementations through templates in the framework , Take a look at the following implementation :
 
template<typename Derived>
class Basic
{
public:
inline void Print() {
SelfCast()->Print();
} protected:
inline Derived* SelfCast() {
return static_cast <Derived*>(this);
}
};
class Derived1 : public Basic<Derived1>
{
public:
Derived1() {} inline void Print() {
std::cout << "Derived1 Print" << std::endl;
}
};
class Derived2 : public Basic<Derived2>
{
public :
Derived2() {} inline void Print() {
std::cout << "Derived2 Print" << std::endl;
} static std::string Name() {
return "Derived2 Class" ;
}
};
 
The specific code used :
 
Basic<Derived1>* der1 = new Derived1();
der1->Print();
Basic<Derived2>* der2 = new Derived2();
der2->Print();
 
Output results :
Derived1 Print
Derived2 Print
The key to this is SelfCast function , adopt static_cast Casts the current object to a specified subclass object , Here is Derived1. In fact, the principle of implementation is very simple , It's not difficult to understand. , What we need to focus on is , What's the difference between polymorphic functions implemented in this way and conventional virtual functions , What are the advantages ?

Everyone should know , The use of virtual functions brings extra overhead , With a virtual function class All types need a virtual function table , And every additional virtual function , The size of the object of the corresponding type increases 4bytes(32 Under the machine ), Exaggeration, imagine if there is 10 A parent class , Every parent has 100 In the case of a virtual function , How much will be added to each object ?
4x10x100=4000bytes!
In addition to the cost of space , Each virtual function call will have one more integer addition and one more pointer indirect reference than ordinary functions in time , That's the cost of time .
This kind of overhead is negligible in most applications , But there will always be some key code that is extremely concerned about performance and overhead . according to 28 The laws of , Application 80% All the time is running in it 20% Code for , Well, sometimes for this 20% The optimization of the code may lead to significant improvements .
Back to the point , We call the traditional implementation dynamic polymorphism , The implementation of template mode is static polymorphism , Sum up their differences :
  1. The polymorphism of dynamic polymorphism is determined at runtime , Static polymorphism is determined at compile time
  2. The implementation of dynamic polymorphism requires more space overhead , Each object is augmented by a virtual function 4bytes, Static polymorphism doesn't have this problem
  3. The implementation of dynamic polymorphism needs more time , Virtual function calls in time than ordinary functions will be one more plastic addition and a pointer indirect reference , The call cost of static polymorphism is the same as that of ordinary function
  4. Dynamic polymorphism ( Virtual functions ) yes C++ An implementation of compiler built-in support , Static polymorphism brings extra complexity to use
  5. In dynamic polymorphism, virtual functions cannot be inlined to optimize execution efficiency , In static polymorphism, the efficiency of function execution can be further optimized by inlining

in summary , In practical use , What kind of implementation do you choose , It depends on the needs , If there are no special performance requirements , There's no need to use templates to make it cool , It's not worth it , But if it's code for specific requirements or critical performance , We can consider this optimization .

Another way to use it , Templates can also achieve static The similar polymorphism of functions , As shown below :
 
template <typename Derived>
class Basic
{
public :
Basic() { } inline void Print() {
std::cout << Basic<Derived>::Name() << std::endl;
SelfCast()->Print();
} static std::string Name() {
return Derived::Name();
} protected :
inline Derived* SelfCast() {
return static_cast <Derived*>( this);
}
}; class Derived1 : public Basic<Derived1>
{
public :
Derived1() {} inline void Print() {
std::cout << "Derived1 Print" << std::endl;
} static std::string Name() {
return "Derived1 Class" ;
}
};
 
That is to say, for some hope, it is defined as static Function of , When you want to use subclasses in base class abstract methods according to the specific type of the current object static Function time , The above method can achieve your goal , This may be a good way to achieve .
ok, So much for static polymorphism , What are the specific applications of extension , Welcome to the discussion .

【C++ Template tour 】 More related articles on the discussion of static polymorphism

  1. 【C++ Template tour 】 One time flexible use in the project C++ Templates (traits) The experience of - New notes

    Problems and needs : Please read this article first ,[C++ Template tour ] One time flexible use in the project C++ Templates (traits) The experience of . For the questions raised in this article , I give you a new idea . talking is cheap,show me t ...

  2. C++ Static polymorphism and dynamic polymorphism in

    C++ Static polymorphism and dynamic polymorphism in Today's C++ It's already a multi generic programming language (multiparadigm programming lauguage), A simultaneous support process form (procedural). Object oriented form ( ...

  3. C++ Advanced -- Static polymorphism

    //############################################################################ /* * polymorphic */ // Common dynamic polymorphisms ...

  4. c++ Macro polymorphism Dynamic polymorphism and static polymorphism ( Reprint )

    Reproduced source : passageway polymorphic (polymorphism) It was originally Greek polumorphos, Meaning is a situation with various forms or forms . In the field of programming , A widely accepted definition is “ One relates different special behaviors to a single generalization token ...

  5. c++ Static polymorphism and dynamic polymorphism

    polymorphic polymorphism It refers to the situation with various forms , It can associate different behaviors based on a single tag . Polymorphism is the foundation of object-oriented programming . Polymorphism in object-oriented programming is a kind of runtime polymorphism .C++ There are two kinds of polymorphisms in , It's called dynamic polymorphism ( Runtime ...

  6. 【C++ Template tour 】 One time flexible use in the project C++ Templates (traits) The experience of

    I once met a very simple problem in a project , But for the time being, we can't solve it very well with ordinary and conventional methods , Finally through C++ Flexible use of templates , adopt traits By contrast, we have skillfully overcome this problem . The main purpose of this paper is to reproduce the occurrence of the problem , A comparison of several solutions ...

  7. Android A journey in reverse --- Static mode analysis and cracking of video editing application 「Vue」 Watermark problem

    One . The story background Now many people like to play literature and art , Especially the ones around me UI People , Take a picture for one minute and revise it for half an hour . It's just to be high in the circle of friends , But it's really pretty , There are too many software for drawing revision, so I won't say much about it , And generally there is no watermark or anything . Compared to short videos, there are ...

  8. c++ polymorphic , Virtual functions 、 overloaded function 、 Template functions

    c++ The three major characteristics : encapsulation . Inherit . polymorphic . Encapsulation makes code modular , Inherits and extends existing code , The purpose of polymorphism is for interface reuse Virtual function implementation : Virtual function table : Pointer to the virtual function table polymorphic : Functions with the same name correspond to different implementations Construct a parent class pointer to an object of a subclass ...

  9. Java Static and dynamic implementation of object-oriented polymorphism

    Briefly : Static polymorphism : Heavy load , Method overloading Dynamic polymorphism : It's rewriting / Cover , Method rewrite

Random recommendation

  1. jmeter Connection mysql and SQL Server To configure

    download jdbc drive In the use of jmeter When doing performance or automation testing , It is often necessary to put pressure on the database directly , Or some parameters can only be obtained from the database , It's time to use jmeter Connect to database . 1. Download the corresponding driver package mysql drive ...

  2. CSS Magic Hall :Box-Shadow It's not that simple :)

    Preface Speaking of box-shadow The first idea, of course, is to achieve shadows , In fact, it can also be used to achieve other fun effects , This article intends to talk about box-shadow Those things . It depends on the effect 3D Pellet <style typ ...

  3. CSS Simulate the parent element selector in

    In many cases , We need to find the parent element , But unfortunately css There is no such selector in . As for the reason, we can see how Zhang Xinxu's life is CSS To achieve the effect of the parent selector in this article . Simply put, this implementation is not really a parent selector , Just use other ideas to ...

  4. Python2.6.6 perform selenium automation

    System type : [root@bogon home]# uname -aLinux bogon 2.6.32-431.el6.x86_64 #1 SMP Sun Nov 10 22:19:54 EST 20 ...

  5. WITH (NOLOCK)

    shortcoming : 1. It will produce dirty reading 2. Only applicable to select Query statement advantage : 1. Some documents say , added WITH (NOLOCK) Of SQL Query efficiency can increase 33%. 2. It can be used for inner join sentence Dirty reading : One use ...

  6. jquery effect - Show and hide Fade in and out slide hide

    jQuery effect - Hide and show :hide() and show() Rules hide / The speed of the display , The following values can be taken :"slow"."fast" Or milliseconds You can use toggl ...

  7. IntelliJ IDEA How to use it in English JUnit4

     background Recently participated in a Anroid Medical programs , There are many basic classes and communication classes at the bottom of the project , And very much involves complex byte operations, as well as multithreading synchronization and state machine processing . Do this kind of project TDD It's still necessary , Try to reduce the risk in the next period . ...

  8. The Linux Mint 17.1:Eclipse Run The C++ And Python Configoration

    p { margin-bottom: 0.1in; line-height: 120% } # Copyright (c) 2016,  Fu Liuwei (Liuwei Fu)# All rights rese ...

  9. solve vsftp Can't start problem ( turn )

    [root@node11 ~]# service vsftpd restartShutting down vsftpd:                                      [F ...

  10. Version control tools --svn and git Use ( One ) ----- The benefits of version control and classification

    Version control tools version control VCS(Version Control Systems) A record of changes in the contents of one or more documents , A system for future reference of revisions to specific versions . This system can automatically back up every change of our files , And you can ...