user3814483
user3814483

Reputation: 312

Enforcing templated base-class types with mixins

I have the following (not meant to compile, but to illustrate the concept efficiently)

class abstract_mixin {
...
}

template<class X>
class concrete_mixin_A : public abstract_mixin, public X {
...
}

Here, abstract_mixin defines a family of mixins, and concrete_mixin_A is one member of that family (there will be _B, _C and so on). Separately, I have a family of classes that any of the mixins in the mixin family are meant to be used with (i.e., the X template parameter above:

class abstract_mixin_compat {

}

class concrete_mixin_compat_A : public abstract_mixin_compat {
...
}

class concrete_mixin_compat_B : public abstract_mixin_compat {
...
}

I can then do concrete_mixin_A < concrete_mixin_compat_B >.

Now I have a third family of classes that operate on an object. I want to limit that to instances of that (logically speaking) conform to abstract_mixin < abstract_mixin_compat >, such that all combinations and derived classes of the above are allowed.

So I have a class with a template parameter T that allows for all types...

template < class T >
class DoStuff {
...
     do_some_stuff( ... accept all instances ... )

     // Possibly also track the instance of T
     T t_instance;
}

How does one achieve this, syntactically or otherwise?

Upvotes: 0

Views: 106

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 120079

Yes it is possible.

template <template <class> class A, class B>
void mixin_checker(const A<B>&) 
   requires (std::is_base_of_v<abstract_mixin, A<B>> && 
             std::is_base_of_v<abstract_mixin_compat, B>)
{}   
              
template <class T>
concept my_mixin = requires(T t) {
    mixin_checker(t);
};

template <my_mixin T> 
class DoStuff {
   ...
};

Upvotes: 1

Related Questions