[英]Template metafunction composition - The Not case
讓我們說我有一個元功能
template<bool, class L, class R>
struct IF
{
typedef R type;
};
template <class L, class R>
struct IF<true, L, R>
{
typedef L type;
};
我想要的是定義一個元函數Not
不會綁定到IF
並返回'反向狀態'。 到目前為止我所擁有的是:
template<bool Cond, typename L, typename R, template<bool, typename,typename> class MF>
struct Not
{
typedef typename MF<!Cond, L, R>::type type;
};
這適用於這種特殊情況。 我的問題是:
boost::mpl
。 誰能提供一個例子? 我可以提出的最通用的解決方案適用於任何類模板采用bool
和任意數量的類型參數 - 包括std::enable_if
:
template<template<bool, typename...> class T, bool arg1, typename... args>
struct Not : T<!arg1, args...> { };
簡單的用法是:
struct bacon {
static const bool tasty = true;
static std::string name() { return "bacon"; }
};
struct spinach {
static const bool tasty = false;
static std::string name() { return "spinach"; }
};
template<typename Food>
typename std::enable_if<Food::tasty>::type eat()
{
::std::cout << "Yummy! " << Food::name() << "!\n";
}
template<typename Food>
typename Not<std::enable_if, Food::tasty, void>::type eat()
{
::std::cout << "Yuck! " << Food::name() << "!\n";
}
和測試用例
eat<bacon>();
eat<spinach>();
會告訴你bacon
是好吃的,而spinach
不是。
您可以使用單個參數制作非模板:
#include <iostream>
template<bool, class L, class R>
struct IF
{
typedef R type;
};
template <class L, class R>
struct IF<true, L, R>
{
typedef L type;
};
template<typename MF>
struct Not;
template<bool Cond, typename L, typename R, template<bool, typename, typename> class MF>
struct Not<MF<Cond, L, R>>
{
typedef typename MF<!Cond, L, R>::type type;
};
struct A { static void print() { std::cout << "A\n"; } };
struct B { static void print() { std::cout << "B\n"; } };
int main()
{
IF<true, A, B>::type::print();
Not<IF<true, A, B>>::type::print();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.