4

我知道它boost::variant使用boost::mpl了它背后的东西并且有一个与 mpl 兼容的 typedef types

假设我有一个简单的 typedef:typedef boost::variant<bool, int> Variant;

现在我有了另一个模板函数,比如说:

template <typename T> T function() {
   // ...
}

我希望这个函数在两种情况下表现不同:当它的T一部分Variant::types和不是的时候。

显然,我必须做类似的事情

template <typename T>
typename boost::enable_if<CONDITION, T>::type function() {
   // Implementation for the case T is in Variant::types
}

template <typename T>
typename boost::disable_if<CONDITION, T>::type function() {
   // Implementation for the case T is ***NOT*** in Variant::types
}

我唯一不知道的是这个CONDITION

现在 - 我确实认为如果TVariant::types.

有人知道怎么做吗?

4

1 回答 1

7

这确实是可能的,Variant::types符合 Mpl.Sequence 类型的要求,因此可以像任何序列一样查询。

因此,boost::mpl::contains这里使用:

// using C++0x syntax to demonstrate what CONDITION should be replaced with
template <typename T>
using Condition = boost::mpl::contains<Variant::types,T>

没有什么比这更简单的了,当你知道的时候;)

如果您需要更多算法,完整的 MPL 手册以HTML格式提供。

于 2010-09-24T19:26:23.167 回答