2010-09-24 30 views
4

我知道boost::variant使用boost::mpl后面的东西,并具有mpl兼容typedef typesC++助推变体问题

比方说,我有一个简单的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的一部分,我认为可以进行编译时查询。

是否有人知道如何?

回答

7

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

因此,使用boost::mpl::containshere

// 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格式提供,如果你需要更多的算法。

+0

+1。由于问题标记为C++而非C++ 0x,因此您可能需要添加有关“using”语法的注释。另外,你是不是故意在'boost :: mpl :: contains'中写'Variant :: types'而不是'Variant'? – sellibitze 2010-09-24 19:34:39

+0

@sellibitze:感谢您检查代码:-) – 2010-09-24 20:53:16