StarKat99
StarKat99

Reputation: 531

Partial Template Specialization of Template

I can't for the life of me get this to work.

I have an existing template:

template <class T>
class MyTemplate;

Now I want to specialize it, but for a class T that's a template--without further specializing the second template, for example:

template <>
template <class T>
class MyTemplate<vector> { /*...*/ };

But this, and various other syntaxes I've tried don't seem to compile. What's the syntax for this? Or is it even possible? If not, are there possible alternatives for MyTemplate so that I could handle, say, a generalized specialization for both vector and map?

Upvotes: 1

Views: 194

Answers (5)

Rose
Rose

Reputation: 11

I'm not sure about the syntax for defining a template for a class. You need to look that up. However defining the template is not the catch all. You need to write the class definition for each template. For example if you have an class define to do talking 1 argument of type x, and taking 2 arguments of type y, or etc... then you need a class to handle it. Same as function overloading . You have the same function name but each takes different arguments. You write a function for each. And that call picks the right function based on the argument list.

So a class that ... will sort different objects by defining for each type.

Upvotes: 0

Matthieu M.
Matthieu M.

Reputation: 300359

A template can be defined either in terms of:

  • non-type parameters (constants)
  • type parameters
  • template parameters

once it has been so defined, any specialization must respect the kind of the parameter.

Therefore, if you want to specialize for a vector (which is a template) where a type parameter is expected, you need to spell out the parameters of the vector to create a (templated) type parameter:

template <typename T, typename Alloc>
class MyTemplate < std::vector<T, Alloc> > {
};

Similarly for map, though there are more parameters:

template <typename K, typename V, typename C, typename A>
class MyTemplate < std::map<K, V, C, A> > {
};

and here you go :)

Upvotes: 0

Walter
Walter

Reputation: 45484

more generally

template<typename A, typename B> class MyTemplate;
template<typename C, typename D> class SomeTemplate;

template<typename A, typename C>
class MyTemplate<A, SomeTemplate<C,A> > { /* ... */ };

Upvotes: 1

David
David

Reputation: 28178

I think you're looking for this:

template<typename T>
class MyTemplate {...}

template<typename T>
class MyTemplate<vector<T> > {...}

Above, the partial specialization is used when you make a MyTemplate<vector<int> > x; and T is int.

Upvotes: 2

BЈовић
BЈовић

Reputation: 64283

The proper syntax is :

template < typename T>
class MyTemplate<vector<T> > { /*...*/ };

Upvotes: 2

Related Questions