【问题标题】:Getting std::complex<double> to pass std::is_floating_point test让 std::complex<double> 通过 std::is_floating_point 测试
【发布时间】:2014-08-17 00:17:57
【问题描述】:

我希望 double、float、complex&lt;double&gt; 和 complex&lt;float&gt; 类型传递 static_assert 条件。我认为static_assert(std::is_floating&lt;T&gt;::value, "some message") 可以解决问题,但是复杂类型没有通过这个测试(至少在 gcc-4.10 下)。

我会添加什么谓词来确保这四种类型(也许还有long doubles)被允许作为模板实例化,但没有别的?

【问题讨论】:

    标签: c++ templates c++11 static-assert


    【解决方案1】:

    为标准库类型特征类添加特化通常是非法的,即使对于用户定义的类型也是如此。 §20.10.2 [meta.type.synop]/p1:

    为任何 本小节中定义的类模板是未定义的,除非 另有规定。

    目前,唯一允许用户为其添加特化的类型特征类是std::common_type,如果特化中的至少一个模板参数是用户定义的类型(§20.10.7.6 [meta.trans.other] , 表 57)。

    你需要写出你自己的特质,这并不难:

    template<class T>
    struct is_complex_or_floating_point : std::is_floating_point<T> { };
    
    template<class T>
    struct is_complex_or_floating_point<std::complex<T>> : std::is_floating_point<T> { };
    

    Demo.

    【讨论】:

    • 尼斯不知道。
    【解决方案2】:

    如果您愿意使用Boost.TypeTraits,他们提供boost::is_complex 与std::complex 一起使用。

    #include <complex>
    #include <type_traits>
    #include <boost/type_traits.hpp>
    
    int main()
    {
        static_assert(std::is_floating_point<float>::value, "some message");
        static_assert(std::is_floating_point<double>::value, "some message");
        static_assert(boost::is_complex<std::complex<float>>::value, "some message");
        static_assert(boost::is_complex<std::complex<double>>::value, "some message");
    }
    

    Live example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多