Boost检查该类型是否属于给定类型的列表

boost check if the type belong to a list of given types

本文关键字:类型 列表 是否 检查 Boost 属于      更新时间:2023-10-16

我有以下问题。在模板中,我想检查类型是否是给定类型之一。

代码描述:

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
};

我知道如何使用模板规范进行操作,但是这种方式很乏味。

   template <typename T>
    class ValidateType
    {
        static const bool valid = false;
    };
    template <>
    class ValidateType<int>
    {
        static const bool valid = true;
    }
    //repeat for every wanted type

有优雅的方式吗?

这有效:

#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

您可以使用contains算法使用MPL vector(这是 type 的向量):

typedef vector<int, long, long long, double> types;
BOOST_MPL_ASSERT(( contains<types, T> ));