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 want 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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top