簡體   English   中英

模板元函數組合 - 非案例

[英]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;
};

這適用於這種特殊情況。 我的問題是:

  1. 有沒有辦法提供更通用的解決方案? (關於我們正在擴展的元函數的參數和功能)
  2. 在C ++中有沒有經過驗證的設計/習語/模式來做這些事情
  3. 我懷疑這可以用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM