静态多态是否对实现接口有意义?

时间:2013-12-25 09:25:35

标签: c++ templates polymorphism static-polymorphism policy-based-design

大家圣诞快乐!

我正在学习静态多态,我正在阅读Andrei Alexandrescu关于基于策略的设计的优秀书籍。我在我的代码中遇到了以下内容:我有接口Interface,它指定方法Foo必须存在。该接口将由类Impl实现。我有以下两种选择:

1)动态多态

class Interface {
public:
    virtual void Foo() = 0;
}

class Impl : public Interface {
public:
    void Foo() {};
}

2)静态多态性

class Impl {
{
public:
    void Foo() {};
}

template <class I>
class Interface : public I
{
public:
    void Foo() { I::Foo(); } //not actually needed
}

在这种情况下使用静态多态是否有意义?与第一种方法相比,第二种方法是否提供了任何好处?接口只指定了某些方法的存在,并且它的机制对于不同的实现是相同的 - 所以不太像本书中描述的情况,所以我觉得我可能只是过于复杂化了。

更新:我在运行时不需要多态行为;在编译时已知正确的实现。

2 个答案:

答案 0 :(得分:4)

检查界面。

动态多态会强制孩子尊重界面。

静态多态性不会强制孩子尊重界面 (直到你真的调用函数),所以,如果你没有提供有用的方法, 您可以直接使用Impl

class InvalidImpl {}; // Doesn't respect interface.
void bar()
{
    InvalidImpl invalid;

    // this compiles, as not "expected" since InvalidImpl doesn't respect Interface.
    CRTP_Interface<InvalidImpl> crtp_invalid; 

#if 0 // Any lines of following compile as expected.
    invalid.Foo();
    crtp_invalid.Foo();
#endif
}

你有第三种方法使用traits检查一个类验证接口:

#include <cstdint>
#include <type_traits>

// Helper macro to create traits class to know if class has a member method
#define HAS_MEM_FUNC(name, Prototype, func)                             \
    template<typename U>                                                \
    struct name {                                                       \
        typedef std::uint8_t yes;                                       \
        typedef std::uint16_t no;                                       \
        template <typename T, T> struct type_check;                     \
        template <typename T = U>                                       \
        static yes &chk(type_check<Prototype, &T::func> *);             \
        template <typename > static no &chk(...);                       \
        static constexpr bool value = sizeof(chk<U>(0)) == sizeof(yes); \
    }

// Create traits has_Foo.
HAS_MEM_FUNC(has_Foo, void (T::*)(), Foo);

// Aggregate all requirements for Interface
template <typename T>
struct check_Interface :
    std::integral_constant<bool, has_Foo<T>::value /* && has_otherMethod<T>::value */>
{};

// Helper macros to assert if class does respect interface or not.
#define CHECK_INTERFACE(T) static_assert(check_Interface<T>::value, #T " doesn't respect the interface")
#define CHECK_NOT_INTERFACE(T) static_assert(!check_Interface<T>::value, #T " does respect the interface")

让我们测试一下:

class Interface {
public:
    virtual void Foo() = 0;
};

class Child_Impl final : public Interface {
public:
    void Foo() override {};
};

#if 0 // Following doesn't compile as expected.
class Child_InvalidImpl final : public Interface {};
#endif

template <class I>
class CRTP_Interface : public I
{
public:
    void Foo() { I::Foo(); } // not actually needed
};

class Impl { public: void Foo(); }; // Do respect interface.
class InvalidImpl {};               // Doesn't respect interface.

CHECK_INTERFACE(Interface);
CHECK_INTERFACE(Child_Impl);
CHECK_INTERFACE(Impl);
CHECK_INTERFACE(CRTP_Interface<Impl>);

CHECK_NOT_INTERFACE(InvalidImpl);
CHECK_INTERFACE(CRTP_Interface<InvalidImpl>); // CRTP_Interface<T> _HAS_ Foo (which cannot be invoked)

性能

使用动态多态性,您可以支付虚拟呼叫费用。您可以通过将final添加为class Child final : public Interface来减少某些虚拟来电。

因此编译器可以优化代码:

void bar(Child& child) { child.Foo(); } // may call Child::Foo not virtually.

但它不能做任何魔法(假设bar没有内联):

void bar(Interface& child) { child.Foo(); } // have to virtual call Foo.

现在,假设你的界面中有:

void Interface::Bar() { /* some code */ Foo(); }

我们处于第二种情况,我们必须虚拟呼叫Foo

静态多态通过:

解决了这个问题
template<class Derived>
void Interface<Derived>::Bar() { /* some code */ static_cast<Derived*>(this)->Foo(); }

答案 1 :(得分:2)

使用静态多态性是否有意义取决于您如何使用该类。

虚函数引入了一个间接层。虚函数允许使用指针或对基类对象的引用(对所有派生类通用)来调用派生类中的方法。

静态polimorphism不使用公共基类。每个派生类都使用它自己的基类。这些基类通常是从公共类模板创建的。然而,他们是不同的阶级。这会导致例如对这些对象的指针或引用不能存储在公共容器中。

相关问题