Getting std :: complex <double> for transition std :: is_floating_point test

I want the types double , float , complex<double> and complex<float> pass the static_assert condition. I figured that static_assert(std::is_floating<T>::value, "some message") would do the trick, but complex types won't pass this test (at least under gcc-4.10).

What predicate would I like to add to make sure that these four types (and possibly long double as well) are allowed as template instances, but nothing more?

+5
source share
2 answers

As a rule, it is forbidden to add specializations for classes of a typical library type, even for custom types. ยง20.10.2 [meta.type.synop] / p1:

The behavior of a program that adds specializations to any of the class templates defined in this subclause is undefined, unless otherwise specified.

Currently, the only type of feature class for which users are allowed to add specializations is std::common_type if at least one template parameter in the specialization is a user-defined type (ยง20.10.7.6 [meta.trans.other], Table 57) .

You need to write your own sign, which is not difficult:

 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

+9
source

If you are ready to use Boost.TypeTraits , they provide boost::is_complex for use with 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"); } 

Living example

+1
source

Source: https://habr.com/ru/post/1200496/


All Articles