2

I have the following class template:

template<typename T, T n> class Some
{
public:
    Some() : v(n) {}
    T get() const { return v ; }
private:
    T v;
};

I happily can specialize on an int, just like:

template <>
class Some<int, 0>
{
public:
    Some() : v(0) {}
    int get() const {return v;}
private:
    int v;
};

However if I try to make the same with float:

template <>
class Some<float, 0>
{
public:
    Some() : v(0) {}
    float get() const {return v;}
private:
    float v;
};

I get ugly compilation errors:

 error: 'float' is not a valid type for a template non-type parameter
     class Some<float, 0>
                    ^

Why? And how can I make the class work for floats also?

Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
  • 2
    because floating point type cannot be treated as non-type template parameter, see e.g. [here](http://stackoverflow.com/documentation/c%2b%2b/460/templates/16713/non-type-template-parameter#t=201608191145444374984) which types are allowed – W.F. Aug 19 '16 at 11:45
  • "making the class work" requires more information on what the class' behaviour should be. You know you can't have a float non-type parameter, but is it OK for `n` to be, say, unsigned long long? – juanchopanza Aug 19 '16 at 11:45
  • 2
    @W.F. yup, that is also what the compiler says... but what is the reasoning behind it? – Ferenc Deak Aug 19 '16 at 11:46
  • @fritzone from "C++ Templates: The Complete Guide" by by Nicolai M. Josuttis; David Vandevoorde: `Not being able to use floating-point literals (and simple constant floating-point expressions) as template arguments has historical reasons. Because there are no serious technical challenges, this may be supported in future versions of C++ (see Section 13.4 on page 210).` Well - the future is not yet now. – marcinj Aug 19 '16 at 12:31

0 Answers0