1

I have a template:

template <typename T, int size>
class Array
{

    T A[size];

public:

    T& operator[](int index) ;

};

template <typename T, int size>
T& Array<T,size>::operator[](int index)
{
    if (index>=size || index<0)
        return A[0];
    else
        return A[index];
}

And its specialisation class:

typedef struct Data
{
    int id;
    char name[10];
    double temp;
    double quantity;
}Data;

template <>
class Array<Data, int>
{
};

And I try to use it:

int main()
{
    Array<Data, int> tab;
    return 0;

}

But I'm getting this error, and dont really know why:

error: type/value mismatch at argument 2 in template parameter list for ‘template class Array’|

What's wrong?

Its strange. I changed the code to the following one:

template <>
class Array<Data, 20>
{
};

int main()
{
    Array<Data, 20> tab;
    return 0;
}

And its ok now. Thanks!

Brian Brown
  • 3,873
  • 16
  • 48
  • 79
  • 3
    Your second template argument expects an `int`, not a type. – tkausl Oct 08 '16 at 12:23
  • @tkausl: When I removed `int`, the error has changed to `error: wrong number of template arguments (1, should be 2)|error: provided for ‘template class Array’|` – Brian Brown Oct 08 '16 at 12:25

1 Answers1

2

I can only guess that what you actually want to create a template specialization for Array<T, size> where T=Data and size is not specified.

template <int size>
class Array<Data, size> // partial specialization
{
};

When you instantiate the template, you have to specify a constant size:

int main()
{
    Array<Data, 5> tab; // size=5 for this example
    return 0;
}
grek40
  • 13,113
  • 1
  • 24
  • 50
  • Yes, that's it! Thank you so much! I have only one question here: can I add a constructor in `Array` class co that I can initialize members of the `Data` struct? – Brian Brown Oct 08 '16 at 12:33
  • @BrianBrown When you create a class specialization, you basically re-write the whole class! Ofcourse you can write a special constructor there. The actual problem may come into play when you **don't** want to re-write parts of the template class for the spezialization. [This question](http://stackoverflow.com/questions/2757816/class-template-specializations-with-shared-functionality) might become relevant then. – grek40 Oct 08 '16 at 12:57