When to prefer templated policy based design over non-templated inheritance based design

后端 未结 2 568
南笙
南笙 2021-02-14 10:44

I am trying to understand the real requirement of the usage of templates for policy based design. Going through the new templated designs in C++ I found that policy based class

相关标签:
2条回答
  • 2021-02-14 11:06

    Depends on the situation I guess... A possible downside of using templates is that the type should be known at compile-time:

    HelloWorld<English> hw; // English is plugged at compile-time
    

    In your second example, where you're using a pointer-to-base, this pointer might point to a variety of derived classes. What exactly it points to is not required to be known at compile-time and can therefore be determined by (user-)input at runtime. A possible down-side of this approach is virtual call overhead. In some applications, and on some platforms, this might be unwanted.

    0 讨论(0)
  • 2021-02-14 11:18

    Both are valid ways of structuring, it actually depends on the requirements. E.g.

    Runtime vs compile time polymorphism.

    When do you want/can/have to achieve polymorphism ?

    Performance overhead of virtual calls

    Templates generate code that has no indirections

    The actual usage of the class.

    When you have to store heterogenous collections, a base class is needed, so you have to use inheritance.

    A very good book on policy-based design (a bit dated but good nevertheless) is Modern C++ Design

    0 讨论(0)
提交回复
热议问题