brance
brance

Reputation: 1178

Template Class with one and two template arguments

I'm trying to create an instance of a Class, that uses templates, but with two possible instantiations.

I have this definition of a class SepChaining with one template argument E.

template <typename E>
class Container {
  ...
}

This is my header file.

template <typename E>
class SepChaining : public Container<E> {
  ...

And in my main.cpp I have the option to do

SepChaining<int>* c = nullptr;

c = new SepChaining<int>;

and

c = new SepChaining<int, 13>;

Of course I am getting an error for the second statement, telling me that there are too many template arguments, but I need a way to implement that option too, to create a instance of the class with 2 parameters. I've read about Partial template specialisation, but I'm not really sure how to implement it.

Any help would be appreciated!

Upvotes: 1

Views: 171

Answers (1)

Peter K
Peter K

Reputation: 1807

You can define you template like this

template <typename E, size_t S = 7>
class SepChaining : public Container<E> {
    ...
}

then you can instantiate it as you suggested

// use default value for S that is 7
c1 = new SepChaining<ElementType>;

and

// specify S = SIZE explicitly
c2 = new SepChaining<ElementType, SIZE>;

of cause c1 and c2 will have different types unless SIZE is 7

Upvotes: 1

Related Questions