开发者

C++ boost variant question

I know that boost::variant uses boost::mpl stuff behind it and has a mpl-compatible typedef types.

Let's say I have a simple typedef: typedef boost::variant<bool, int> Variant;

Now I have another template function, let's say:

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

I wa开发者_JAVA百科nt this function to act differently for two cases: when T a part of Variant::types and when it's not.

Obviously, I have to do something like

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
}

The only thing I don't know is this CONDITION.

Now - I do think it's possible to make a compile-time query if T is a part of Variant::types.

Does someone know how?


It is indeed possible, Variant::types meets the requirement of a Mpl.Sequence type and therefore can be queried like any sequence.

Therefore, using boost::mpl::contains from here:

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

Nothing simpler, when you know about it ;)

The full MPL Manual is available in HTML format, should you need some more algorithms.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜