【问题标题】:boost check if the type belong to a list of given typesboost 检查类型是否属于给定类型的列表
【发布时间】:2014-02-04 09:21:18
【问题描述】:

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

代码说明:

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

有没有优雅的方法?

【问题讨论】:

    标签: c++ templates boost


    【解决方案1】:

    这行得通:

    #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
    

    【讨论】:

    • 您好,如何扩展 allowed_types 列表,例如在单个断言语句中允许 vector
    • 我想我不明白你想要达到什么目的。
    • 假设我想允许 boolstd::stringint 以及 std::vector&lt;bool&gt;std::vector&lt;std::string&gt;std::vector&lt;int&gt; 而不在 mpl::set 他们的矢量风格中明确提及。
    • 我从 C++ 继续前进,所以我的知识可能有点生疏。话虽如此,我认为应该可以编写一个映射T -&gt; Tvector&lt;T&gt; -&gt; Tdrop_vector 元函数。在这种情况下,您可以在allowed_types 中查询drop_vector&lt;T&gt;::type。如果您需要这方面的帮助(或者如果我承诺过多),最好提出一个新问题。
    【解决方案2】:

    您可以在contains 算法中使用MPL vector(它是一个类型的向量):

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

    【讨论】:

    • 它不工作,"typedef boost::mpl::vector types; BOOST_MPL_ASSERT(( contains )); " 编译通过跨度>
    猜你喜欢
    • 2015-02-19
    • 1970-01-01
    • 2022-01-25
    • 2011-03-21
    • 1970-01-01
    • 2012-06-10
    • 2022-01-25
    • 2019-01-05
    • 2012-10-26
    相关资源
    最近更新 更多