【问题标题】: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<double> 和 complex<float> 类型传递 static_assert 条件。我认为static_assert(std::is_floating<T>::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