6

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?

1
  • Also see this related question. Commented Nov 3, 2010 at 9:23

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

7 Comments

@Nim but how would you do (your way) and represent 1.02?
@There: You could wrap the constant in a struct and use that as a parameter for the template.
@Space, not sure that is that @There wants, X<double_struct> is significantly different to X<double N> - unless I'm missing something...
@Space yes but, and I repeat myself, how would you go with 1.02?
@There, pretty much... internally this is then a trivial calculation, double v = static_cast<double>(M) * ::exp10(static_cast<double>(E));
|
5

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.

2 Comments

I would hazard that X<1+1> would infact be of type X<int N>! ;) we know you mean X<1.0 + 1.0> x; ! ;)
1.0 + 1.0 is guaranteed to be 2.0 in any floating-point implementation. Something like 0.6 + 1.4 would not be, as those numbers are not representable as non-repeating fractions in binary.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.