策略和CRTP的静态多态性有什么区别?

Dan*_*tor 8 c++ inheritance design-patterns crtp static-polymorphism

我希望在编译时选择具有多个可能实现的接口.我看到CRTP是实现它的首选成语.这是为什么?另一种选择是策略模式,但我在任何地方都没有提到这种技术:

template <class Impl>
class StrategyInterface
{
public:
    void Interface() { impl.Implementation(); }
    void BrokenInterface() { impl.BrokenImplementation(); }

private:
    Impl impl;
};

class StrategyImplementation
{
public:
    void Implementation() {}
};

template <class Impl>
class CrtpInterface
{
public:
    void Interface() { static_cast<Impl*>(this)->Implementation(); }
    void BrokenInterface() { static_cast<Impl*>(this)->BrokenImplementation(); }
};

class CrtpImplementation : public CrtpInterface<CrtpImplementation>
{
public:
    void Implementation() {}
};

StrategyInterface<StrategyImplementation> str;
CrtpImplementation crtp;
Run Code Online (Sandbox Code Playgroud)

BrokenInterface遗憾的是,在任何一种情况下,编译器都没有捕获它,除非我真的尝试使用它.策略变体对我来说似乎更好,因为它避免了丑陋static_cast,它使用组合而不是继承.还有什么CRTP允许的,那个策略没有?为什么主要使用CRTP?

Tor*_*zki 1

策略模式的通常实现与 CRTP 实现完全相同。基类定义某种算法,放出一些在派生类中实现的部分。

因此CRTP实现了策略模式。您的 StrategyInterface 只是委托了细节的实现,而不是策略模式的实现。

虽然您的两种实现都达到了相同的效果,但我更喜欢 CRTP,因为它会利用可能的空基类优化。