2010-09-24 34 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