C++提升变体问题

Yip*_*Yay 4 c++ boost variant compile-time boost-mpl

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

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

现在我有另一个模板功能,让我们说:

template <typename T> T function() {
   // ...
}
Run Code Online (Sandbox Code Playgroud)

我希望这个函数在两种情况下采取不同的行动:当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
}
Run Code Online (Sandbox Code Playgroud)

我唯一不知道的是这个CONDITION.

现在 - 我认为如果T是其中的一部分,可以进行编译时查询Variant::types.

有人知道吗?

Mat*_* M. 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>
Run Code Online (Sandbox Code Playgroud)

什么都不简单,当你知道它;)

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