简体   繁体   English

如何将浮点值用作非类型模板参数?

[英]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? 是否有任何理由不能将double作为参数类型与模板?
For example: 例如:

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

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

Is there any update on this in C++11? 在C ++ 11中是否有任何更新?

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? 鉴于浮点算术只给出模糊结果( sqrt(2.0)*sqrt(2.0)可能不等于2.0 ),你如何建议使用double作为模板参数可能有用? 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. 我会说这严重限制了它的用处,我称之为残废。

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... 考虑使用整数尾数和指数作为模板参数...

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> 使用巧妙的元编程技术,您甚至可以将它们降低到最低项,因此如果使用有理数,那么X <3,6>将与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. 考虑这是否真的是正确的实践方法,还是仅仅是元编程中的练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM