Nik*_*iou 3 c++ templates metaprogramming
让我们说我有一个元功能
template<bool, class L, class R>
struct IF
{
typedef R type;
};
template <class L, class R>
struct IF<true, L, R>
{
typedef L type;
};
Run Code Online (Sandbox Code Playgroud)
我想要的是定义一个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;
};
Run Code Online (Sandbox Code Playgroud)
这适用于这种特殊情况.我的问题是:
boost::mpl.谁能提供一个例子?我可以提出的最通用的解决方案适用于任何类模板bool和任意数量的类型参数 - 包括std::enable_if:
template<template<bool, typename...> class T, bool arg1, typename... args>
struct Not : T<!arg1, args...> { };
Run Code Online (Sandbox Code Playgroud)
简单的用法是:
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";
}
Run Code Online (Sandbox Code Playgroud)
和测试用例
eat<bacon>();
eat<spinach>();
Run Code Online (Sandbox Code Playgroud)
会告诉你这bacon是美味的,而spinach不是.
| 归档时间: |
|
| 查看次数: |
197 次 |
| 最近记录: |