Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doubles as template type?

I am trying to create a generic class that handles ints, doubles, and strings. However, when trying to instantiate the template class with I get the following error message:

error: 'double' is not a valid type for a template constant parameter

The instantiation works completely fine with int types, as does the internal code, though I haven't made it to string types yet. It seems as if this should be fine, since you can instantiate vector, etc. Is there something I am missing here?

// file forest.h

template<typename NODETYPE> class Forest
{
    template<NODETYPE>                                              // Line 15
    friend Forest<NODETYPE>& operator+(Forest<NODETYPE>& f1,
                                       Forest<NODETYPE>& f2);

    template<NODETYPE>                                              // Line 17
    friend ostream& operator<<(ostream& output,
                               const Forest<NODETYPE>& f1);

    template<NODETYPE>                                              // Line 19
    friend void outputHelper(ostream& output,
                             const ForestNode<NODETYPE>& currentNode,
                             int depth);
    /* ... */
};

The error occurs as follows:

\project 4\forest.h|341|instantiated from here|
\project 4\forest.h|15|error: 'double' is not a valid type for a template constant parameter|
\project 4\forest.h|17|error: 'double' is not a valid type for a template constant parameter|
\project 4\forest.h|19|error: 'double' is not a valid type for a template constant parameter|
like image 754
joedillian Avatar asked Jul 31 '26 17:07

joedillian


2 Answers

template<NODETYPE> friend Forest<NODETYPE>& operator+(Forest<NODETYPE>& f1, Forest<NODETYPE>& f2);

    template<NODETYPE> friend ostream& operator<<(ostream& output, const Forest<NODETYPE>& f1);

    template<NODETYPE> friend void outputHelper(ostream& output, const ForestNode<NODETYPE>& currentNode, int depth);

These friend declarations are invalid. If you have a templated class, you don't need to repeat it's template arguments when referring to it within it's own scope. Even if you intended to allow any other instantiation of Forest, then you would have to use typename or class and call NODETYPE something else.

like image 183
Puppy Avatar answered Aug 02 '26 12:08

Puppy


You can use double (or float or long double) as a template parameter with any compiler that's even sort of close to conforming. What you can't do is use a floating point value as a non-type template parameter.

The closest you can get to this is generally passing the floating point value(s) to the ctor, and store it/them in your object.

like image 22
Jerry Coffin Avatar answered Aug 02 '26 11:08

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!