Search code examples
c++boost-fusion

Can/should i inherit from a Boost.Fusion sequence?


Can/should i inherit from a Fusion sequence to implement my own sequence class? If no, why not?

For example:

typedef boost::fusion::vector<
    std::vector<const char*>, 
    int, 
    double > MyVector;

class MyVectorWithData : public MyVector
{
public:
    MyVectorWithData(int i); // Constructor does some initialization
    // may be other member functions acting on baseclass MyVector
};

Solution

  • Like standard containers, Fusion containers do not provide a virtual destructor, so the same arguments against extending them hold.

    In addition to that, in my experience, template metaprogramming and inheritance does not combine seamlessly. The main problem is that base classes are not considered to select template specializations, which means that if some metafunctions is specialized for fusion::vector, you will not be able to use it with your type deriving from fusion::vector.

    If I remember correctly, Fusion uses tag dispatching along with trait classes to select implementations, so this might be an issue. I think the default trait class simply "forward" a nested typedef, so that could work here since the typedef will be inherited, but I am not sure this is reliable (implementation could change).

    Finally, Fusion containers does not provide any member functions (except those needed for construction and assignment), so there is little use deriving from them. If you want your class to be compatible with Fusion (meta)functions, you should use the extension mechanism provided by the library.