lundi 26 septembre 2016

type providing bases classes (or noncopyable) and virtual inheritance

I've in the past used base classes purely for making type information constant (similar to traits classes, as well as perhaps ios_base). These classes would typically have no data, but only provide types that are commonly used (perhaps decorating an original type), the idea being in the event of change, changing the type constant at one location. I've been wondering if there are any advantages in using virtual inheritance for interfaces that might inherit from such type classes. A well known example of a similar case is interfaces that may derive boost::noncopyable (not that I often use boost::noncopyable for interfaces).

Here follows a little example of the case in question:

#include <iostream>
#include <memory>


struct Path{};

struct SomeTypeDefs //Or something providing services similar boost::noncopyable
{
    typedef std::shared_ptr<Path> PathPtr;
};


struct InterfaceX : SomeTypeDefs
{
    virtual PathPtr getPathX() const = 0;
};

struct InterfaceY : SomeTypeDefs
{
    virtual PathPtr getPathY() const = 0;
};

struct Impl : InterfaceX, InterfaceY
{
    private:

    virtual PathPtr getPathY() const{ return PathPtr{}; }
    virtual PathPtr getPathX() const{ return PathPtr{}; }
};

void foo(const InterfaceX&)
{
    std::cout << "foo X" << std::endl;
}
void foo(const InterfaceY&)
{
    std::cout << "foo Y" << std::endl;
}

int main() 
{
    Impl impl;
    foo(static_cast<InterfaceX&>(impl));
    foo(static_cast<InterfaceY&>(impl));
    return 0;
}

I can't see the benefit of using virtual inheritance in this case (is there any)?

Aucun commentaire:

Enregistrer un commentaire