How to use a floating point value as a parameter of a non-piggy type template?

Is there a reason why you cannot have a double parameter type with templates?
For example:

template<int N>//-< Legal struct { }; template<double N>//-< Illegal struct { }; 

Is there an update in C ++ 11?

+6
c ++ c ++ 11 templates
source share
3 answers

This is due to accuracy, floating point numbers cannot be accurately represented, and the likelihood that you are referring to the same type may depend on how the number is represented. Instead, consider using the integer mantissa and exponent as template parameters ...

+5
source share

Given that floating point arithmetic gives only fuzzy results ( sqrt(2.0)*sqrt(2.0) may not be equal to 2.0 ), how do you suggest using double as template arguments? If you have a template

 template<double D> // not allowed in C++ class X {}; 

and specialize in that

 template<> class X<2.0> {}; 

then

 X<1.0+1.0> x; 

may not refer to specialization.

I would say that it limits its usefulness so much that I would call it crippled.

+5
source share

You can only use integral types for template parameters, but you can fool your way into using fractional values ​​using two integers: one as a mantissa and one as an exponent, or one as a numerator, and one as a denominator. Using the smart metaprogram method, you can even reduce them to the lowest values, so if you use rational methods, then X <3,6> will work the same as X <1,2>

What you can do and what you must do is not necessarily the same. Think about whether this is the right practical approach or just an exercise in the metaprogram.

+2
source share

All Articles