Reputation: 1012
I have the following problem. In the template, I want to check if the type is one of the given types.
Code description:
tempalte <typename T>
class foo
{
public:
//BOOST_STATIC_ASSERT(T is one of int, long, long long, double ....);
//boost::is_scalar doesn't fill my requirements since I need
//to provide my own list of types
};
I know how to do it using the template specification, but this way is tedious.
template <typename T>
class ValidateType
{
static const bool valid = false;
};
template <>
class ValidateType<int>
{
static const bool valid = true;
}
//repeat for every wanted type
Is there elegant way?
Upvotes: 2
Views: 1086
Reputation: 2504
This works:
#include <boost/mpl/set.hpp>
#include <boost/mpl/assert.hpp>
typedef boost::mpl::set<int, long, long long, double, ...> allowed_types;
BOOST_MPL_ASSERT((boost::mpl::has_key<allowed_types, int>)); // Compiles
BOOST_MPL_ASSERT((boost::mpl::has_key<allowed_types, char>)); // Causes compile-time error
Upvotes: 4
Reputation: 110658
You can use an MPL vector
(which is a vector of types) with the contains
algorithm:
typedef vector<int, long, long long, double> types;
BOOST_MPL_ASSERT(( contains<types, T> ));
Upvotes: 1