简体   繁体   中英

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;
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM