How can I use a floating-point value as a non-type template parameter?
Is there any reason for not being able to have double as a parameter type with templates?
For 开发者_Python百科example:template<int N>//-< Legal
struct
{
};
template<double N>//-< Illegal
struct
{
};
Is there any update on this in C++11?
This is to do with precision, floating point numbers cannot be precisely represented, and the likelyhood of you referring to the same type can depend on how the number is represented. Consider instead using an integer mantissa and exponent as the template parameters...
Given that floating point arithmetics only give fuzzy results (sqrt(2.0)*sqrt(2.0)
might not be equal 2.0
), how do you propose using double
as template arguments could be useful? If you had a template
template<double D> // not allowed in C++
class X {};
and specialize that
template<>
class X<2.0> {};
then
X<1.0+1.0> x;
might not refer to the specialization.
I'd say that limits its usefulness so severely that I'd call it crippled.
You can only use integral types for template parameters but you can cheat your way into using fractional values by using two integers, one as mantissa and one as exponent or one as numerator and one as denominator. With clever meta-programming technique you can possibly even reduce them to their lowest terms so if you use rationals then X<3,6> will work the same as X<1,2>
What you can do and what you should do are not necessarily the same. Consider whether this is really the right practical approach or just an exercise in meta-programming.
精彩评论