Search code examples
c++mixins

C++ Mixin, check if templated type implements certain mixin


Given a codesnippet that looks like this, how can i write a function, that checks if a given object implements a certain mixin? I tried using pointer-casting but since they have the same base every resoult was non-null, but I am guessing there is a templated solution, but couldn't find any I could implement.

class Widget{
public:
  int px;
  int py;
};

template <typename Base> 
class StaticText : public Base{
public:
  std::string text; 
};

template <typename Base> 
class Alignable : public Base{
public:
  std::string alignment;
};

template <typename Base> 
class Colorable : public Base{
public:
  std::string color;
};

typedef Alignable<StaticText<Widget>> Text;

int main(){
  auto w = std::make_unique<Text>();

  // if(w == Colorable...) 
  // if(w == Alignable...) 

  std::cin.get();
  return 0;
}

Solution

  • You could do something like this:

    template <template <class> class Z, class T>
    class implements_mixin
    {
        template <class U>
        static std::true_type  test(Z<U>* );
        static std::false_type test(... );
    
    public:
        using type = decltype(test(std::declval<T*>()));
        static constexpr bool value = type::value;        
    };
    
    template <class T>
    using isColorable = implements_mixin<Colorable, T>;
    
    // etc.
    

    If there exists a U such that T inherits from Z<U>, we consider that mixin implemented. So implements_mixin<Colorable, Test>::type is std::false_type, but implements_mixin<StaticText, Text>::type is std::true_type.