C ++: specifying a base class for a template parameter

I need to create a framework that computes the result of the divide-et-conquest algorithm in parallel. To use the framework, the user needs to somehow specify a procedure that implements the โ€œdivisionโ€ phase (function from T to T), the โ€œwinโ€ phase (function from D to D), and T and D themselves.

I thought it would be nice to define two abstract classes: BaseDivideand BaseConquer, which declares a pure virtual method computewith the correct types: this way I have a type, (in terms of structure) with a user-defined function that is enabled through the output of abstract classes.

I was thinking of using templates to pass types to the framework, so the user does not need to create them to use the framework, so something like this:

template <typename T, typename D, typename Divide, typename Conquer> 
D compute(T arg);

My problem is that I want Divide and Conquer to be derived types BaseDivideand BaseConquer: is there a way to force it at compile time? Also: do you think I can achieve a similar result with a cleaner design?

+5
source share
3 answers

You can create base classes as follows:

struct BaseDivide {
    enum EnumDiv { derivedFromBaseDivide = true };
}

template <typename T, typename D, typename Divide, typename Conquer> 
    static_assert(D::derivedFromBaseDivide);
    D compute(T arg);

What is the purpose of the advanced options for the Divide and Conquer template? Are you sure you need them?

+3
source

. BaseDivide BaseConquer, .

+2

Use Boost.EnabelIf to run SFINAE if your types do not meet your requirements. Checking that T is obtained from U is doen with boost :: is_base_of:

#include <boost/type_traits/is_base_of.hpp>
#include <boost/enable_if.hpp>

template <typename T, typename D, typename Divide, typename Conquer> 
typename boost::
enable_if_c< boost::is_base_of<BaseDivide,Divide>::value 
          && boost::is_base_of<BaseConquer,Conquer>::value
          ,D
          >::type
compute(T arg);
+2
source

All Articles