Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 example:

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

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

Is there any update on this in C++11?

like image 433
There is nothing we can do Avatar asked Nov 03 '10 09:11

There is nothing we can do


People also ask

Which parameter is allowed for non-type template?

Which parameter is legal for non-type template? Explanation: The following are legal for non-type template parameters:integral or enumeration type, Pointer to object or pointer to function, Reference to object or reference to function, Pointer to member.

Can we use non-type parameters as arguments template?

Non-type template arguments are normally used to initialize a class or to specify the sizes of class members. For non-type integral arguments, the instance argument matches the corresponding template parameter as long as the instance argument has a value and sign appropriate to the parameter type.

How do I restrict a template type in C++?

There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.

Can template parameters have default values?

Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char.


2 Answers

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...

like image 124
Nim Avatar answered Sep 20 '22 02:09

Nim


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.

like image 32
sbi Avatar answered Sep 22 '22 02:09

sbi