Non-template Definition Error

C

crjjrc

I'm having trouble figuring out a problem in the following code:

template<class T, int ndims>
class NFieldBase {
public:
static const T max;
};

template<int ndims> const float NFieldBase<float, ndims>::max = 1.0f;

When compiled with g++, I get this error:

test.cpp:7: error: template definition of non-template ‘const float
NFieldBase<float, ndims>::max’

Especially confounding is that if I take out every instance of the
ndims template parameter, this code compiles just fine. Has g++
spoiled me and should this not compile in general? Or is there
something different I must be doing if I have more than one parameter?

I appreciate any help.

- Chris
 
C

crjjrc

It's allowed for member functions, and I believe for member types.  It
sounds from the OP like this is only an error for partial
specializations.  Strange.

I understood it to be true for static members, as I am using here.
And yes, the issue only arises when I partially specialize.
Anyway, one work-around is:

template<class T, int ndims>
struct NFieldBase
{
     static T const max;

};

template<int ndims>
struct NFieldBase<float, ndims>
{
     static float const max;

};

template<int ndims>
float const NFieldBase<float, ndims>::max = 1.0f;

My real class is much more unwieldy than this small example, and I
need to handle many other types, so this solution isn't practical.
Bummer.

- Chris
 
C

crjjrc

You could define little traits classes like these, and just use the in
the primary template definition for your bigger classes.

Great idea. In fact, a traits classes eliminates the partial
specialization altogether, since my static data members are dependent
only on the type. Easy fix, thanks to your suggestion.

- Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,588
Members
45,100
Latest member
MelodeeFaj
Top