模板元函数组合 - 非案例

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)

这适用于这种特殊情况.我的问题是:

  1. 有没有办法提供更通用的解决方案?(关于我们正在扩展的元函数的参数和功能)
  2. 在C++中有没有经过验证的设计/习语/模式来做这些事情
  3. 我怀疑这可以做到boost::mpl.谁能提供一个例子?

gha*_*.st 5

我可以提出的最通用的解决方案适用于任何类模板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不是.