Search code examples
c++templatesmethodsspecializationmixins

How do I implement polymorphic behavior between two mixin templates?


I'm implementing mixins using C++ templates to support some "extended" behaviors for a base (templated) class.

template< class Ch > Base {...};

template< class T > M1 : public T {...};
template< class T > M2 : public T {...};
// etc.

I need to modify the behavior in one mixin if another mixin is present in the inheritance graph. (Ideally, this would be without regard to which one mixed in first, but I'm willing to accept the restriction that they must derive in a particular order.)

In other words, if I have:

typedef Base< char > base;
typedef M2< M1< base >> foo;
typedef M2< base > bar;

The behavior of the M2 methods needs to change when M1 is mixed in - M1 provides data members that need to be used in the computation of M2 results. On the other hand, M2 makes certain guarantees about those data members that are completely invalid if M2 is not mixed in.

My question, then, is how to implement this C++ '03?

I suspect that there is a way using a template method and specialization, but my template-fu is not powerful enough (yet).


Per dauphic's response, I tried this, and it does work. The need to totally duplicate the M2 template is horrible enough that I'm going to try the SFINAE approach next.

#include <iostream>
#include <UnitTest++.h>

SUITE( Mixin_specialization_tests ) {

    template< typename Ch > struct Base {
        typedef Ch * pointer_type;
        pointer_type p;
    };

    template< class T > struct M1 : public T {
        typedef typename T::pointer_type pointer_type;
        pointer_type m1p;
    };

    template< class T > struct M2 : public T {
        typedef typename T::pointer_type pointer_type;
        pointer_type m2p;

        int compute( ) {
            std::cout << "unspecialized compute()" << std::endl;
            return 0;
        }
    };

    template< >
    template< class B > struct M2< M1<B> > : public M1<B> {
        typedef typename M1< B >::pointer_type pointer_type;
        pointer_type m2p;

        int compute( ) {
            std::cout << "specialized compute()" << std::endl;
            int unused = M1< B >::m1p - m2p;
            return 1;
        }
    };

    typedef Base< char > Bch;
    typedef M1< Bch > M1b;
    typedef M2< Bch  > M2b;
    typedef M2< M1< Bch > > M2m1b;

    TEST( unspecialized ) {
        M2b m2b;
        CHECK_EQUAL( 0, m2b.compute() );
    }

    TEST( specialized ) {
        M2m1b m2m1b;
        CHECK_EQUAL( 1, m2m1b.compute( ) );
    }
}

After struggling for a bit, I managed to get the SFINAE variant working as well. The code is mostly the same except for this part:

    template< class Query > struct is_M1 {
    typedef char yes, (&no)[ 2 ];
    static no has_m1_member(...);

    template< class T, typename T::pointer_type T::* > struct dummy {};
    template< class T >
    static yes has_m1_member( T*, dummy<T, &T::m1p>* = 0 );
    BOOST_STATIC_CONSTANT( bool, value =
        ( sizeof( has_m1_member( ( Query * )0 ) ) == sizeof( yes ) )
    );
};

template< class T > struct M2 : public T {
    typedef typename T::pointer_type pointer_type;
    pointer_type m2p;

    int compute( ) {
        return compute_impl<T>( );
    }

    template< typename B >
    typename boost::enable_if< is_M1< B >, int >::type compute_impl( ) {
        std::cout << "sfinae: m1-compute" << std::endl;
        return 1;
    }

    template< typename B >
    typename boost::disable_if< is_M1<B>, int >::type compute_impl( ) {
        std::cout << "sfinae: non-m1-compute" << std::endl;
        return 0;
    }
};

As I mentioned below, the enable_if<> template doesn't handle boolean expressions (for me), so I went with disable_if<>, which seems to do the trick.

Neither of these is particularly happy-making, since this code is going to be contributed to a project that doesn't currently use boost, and since the option of duplicating the entire template is a maintenance nightmare. But they do both get the job done. I'm going to consider the boost solution the answer, simply because there's a hope that the boost code will become standard, and thus less of a headache.

Thank you all.


Solution

  • As dauphic suggested, you can just do a partial specialization of the M2 class for the case when its argument is a M1, and of course, you can do the same for M1 (with a simple interleaving of the declarations).

    However, this will give you very coarse-grained specialization, i.e., you will have to redefine all the members of M2. This can be annoying if there are only a few members that need to be different, i.e., this solution doesn't scale well. Unfortunately and annoyingly, C++ does not provide support for specializing the member functions independently.

    Nevertheless, Sfinae can come to help you with that, but it requires a bit more work. The following is basically just a classic Sfinae method to allow specialization of individual member functions of a class template:

    #include <iostream>
    #include <boost/utility/enable_if.hpp>
    #include <boost/config.hpp>
    
    template <class Model>
    struct is_M1
    {
        typedef char yes;
        typedef char (&no)[2];
    
        template <class T, void (T::*)()>
        struct dummy {};
    
        template <class T>
        static yes has_m1_function1(T*, dummy<T,&T::function1>* = 0);
        static no has_m1_function1(...); 
    
        BOOST_STATIC_CONSTANT(
            bool
          , value = sizeof( has_m1_function1((Model*)0) ) == 1 );
    };
    
    template <typename T>
    struct Base { T value; };
    
    template <typename T>
    struct M1 : public T {
      void function1() { }; //I presume M1 would have at least one defining characteristic or member function
    };
    
    template <typename T>
    struct M2 : public T {
      void function2() { function2_impl<T>(); };
      template <typename B>
      typename boost::enable_if< is_M1<B>, void>::type function2_impl() { 
        std::cout << "M1 is mixed in T" << std::endl;
      };
      template <typename B>
      typename boost::enable_if< !is_M1<B>, void>::type function2_impl() { 
        std::cout << "M1 is not mixed in T" << std::endl;
      };
    };
    
    int main() {
      M2< M1< Base<int> > > m2m1b;
      M2< Base<int> > m2b;
    
      m2b.function2();
      m2m1b.function2();
    };