Ben Jaguar Marshall
Ben Jaguar Marshall

Reputation: 493

Template specialisation where parameter is non-type parameterized template for metaprogramming

I have the following code:

template<int lengthAfter>
class VariableString{
    public:
        enum{
            fieldSize = -1000
        };

....

};

template<typename T, int FieldSize = sizeof(T)>
class field_trait{
    public:
        enum{
            fieldSize = FieldSize
        };

....
};

template<int lengthAfter>
class field_trait<VariableString<lengthAfter>, -1000>{
    public:
        enum{
            fieldSize = -1000
        };
....
};

static_assert(field_trait<VariableString<0> >::fieldSize == -1000, "VariableString length error");

When I compile, the static_assert fails where I would expect the specialisation to work. Where am I going wrong?

Upvotes: 1

Views: 57

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 120079

Your specialization is only good for the second argument of -1000, but it is sizeof(first argument) as the default in the main template says. That is, your invocation is really equivalent to

field_trait, sizeof (VariableString<0>)>

Do this

template<int lengthAfter, int size>
   class field_trait<VariableString<lengthAfter>, size>

Upvotes: 1

Related Questions