[英]C++ Mixin, check if templated type implements certain mixin
給定一個看起來像這樣的代碼片段,如何編寫一個函數,檢查給定的對象是否實現了某個混合? 我嘗試使用指針轉換,但由於它們具有相同的基礎,每個resoult都是非null,但我猜有一個模板化的解決方案,但找不到任何我可以實現的。
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;
}
你可以這樣做:
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.
如果存在U
使得T
繼承自Z<U>
,我們認為mixin已實現。 所以implements_mixin<Colorable, Test>::type
是std::false_type
,但implements_mixin<StaticText, Text>::type
是std::true_type
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.