Does static polymorphism make sense for implementing an interface?
Asked Answered
R

2

6

and Merry Christmas everybody!

I am learning about static polymorphism and I'm reading Andrei Alexandrescu's excellent book on policy-based design. I came across the following, in my code: I have interface Interface which specifies that method Foo must be present. This interface will be implemented by class Impl. I have the following two options:

1) Dynamic polymorphism

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

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

2) Static polymorphism

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

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

Does it make sense to use static polymorphism in this case? Does the second approach offer any benefits compared to the first one? The interface specifies only the presence of some methods, and its mechanics are the same for different implementation - so not quite like the cases described in the book, so I feel I may only be over-complicating things.

Update: I do not need polymorphic behaviour at run-time; the correct implementation is known at compile-time.

Ramsey answered 25/12, 2013 at 9:25 Comment(6)
The second approach offers absolutely no benefits compared to the second one. ;-)Maverick
See the Benefits and Drawbacks in Wiki: en.wikipedia.org/wiki/…Barbershop
are you trying to understand how to shift from Java interfaces to C++ ?Streamlined
no, I don't know Java.Ramsey
You can use Interface::Foo(); in the first example so the call to the base class makes no difference. But there is a benefit to the second solution when you have multiple base classes which implement the Foo function. If so when using the subclass the correct base class can be chosen by doing this: Interf<Impl>Kendyl
This is precisely my situation, I have multiple classes that implement Foo(), and the correct class is known at compile-time. What is the benefit?Ramsey
P
5

Checking Interface.

Dynamic polymorphism does force the child to respect the interface.

Static polymorphism does NOT force the child to respect the interface (until you really call the function), So, if you don't provide useful method, you may use directly 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
}

You have a 3rd way using traits to check that a class verify an Interface:

#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")

With C++20 concepts, traits can be written differently:

// Aggregate all requirements for Interface
template <typename T>
concept InterfaceConcept = requires(T t)
{
    t.foo();
    // ...
};

#define CHECK_INTERFACE(T) static_assert(InterfaceConcept<T>, #T " doesn't respect the interface")

Lets test it:

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)

Performance

With Dynamic Polymorphism, you may pay for virtual call. You may reduce some virtual call by adding final as class Child final : public Interface.

So compiler may optimize code like:

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

but it can't do any magic (assuming bar not inlined) with:

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

Now, assume that in your interface you have:

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

we are in the second case where we have to virtual call Foo.

Static polymorphism solves that by:

template<class Derived>
void Interface<Derived>::Bar() { /* some code */ static_cast<Derived*>(this)->Foo(); }
Pulpy answered 25/12, 2013 at 11:57 Comment(1)
How about checking interface using: using Derived::func?Weatherwise
Z
2

Whether it makes sense to use static polymorphism depends on how you use the class.

Virtual functions introduce a level of indirection. Virtual functions allow calling a method in the derived class using a pointer or reference to an object of the base class (which is common to all derived classes).

Static polimorphism does not use a common base class. Each derived class uses it's own base class. These base classes are often created from a common class template. Nevertheless, they are different classes. This leads to such things that e.g. pointers or references to such objects cannot be stored in a common container.

Zirconia answered 25/12, 2013 at 9:34 Comment(4)
In my example, the interface class is the derived class (for the static example). In both cases, I can call Interface.Foo().Ramsey
@DanNestor No. In your example you'll have Interface<X>.Foo() and Interface<Y>.Foo() but Interface<X> and Interface<Y> are 2 different classes. You cannot store a Interface<Y> in a std::vector<Interface<X>> and vice-versa.Mesics
Oh, I understand, thanks. However, I do not need polymorphic behaviour at run-time, I will update the question.Ramsey
Very good point on "pointers or references to such objects cannot be stored in a common container.". Have not think about it from that perspective before.Weatherwise

© 2022 - 2024 — McMap. All rights reserved.