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

代码说明:

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

07-24 09:44
查看更多