gerardw
gerardw

Reputation: 6330

C++ template; partial specialization implementation

Given a template class with a single parameter, I can define an implementation for a specific specialization:

template<int N>
struct Foo {
    Foo( );
};

Foo<2>::Foo( ) { //works (on MS Visual 2012, even though it's not the most correct form)
}

For a multiple parameter template, is it possible to define an implementation for a partial specialization?

template <class X, int N>
struct Bar {
    Bar( );
};

template <class X>
Bar<X,2>::Bar( ) { //error
}

Upvotes: 3

Views: 724

Answers (2)

Saksham
Saksham

Reputation: 9380

You need to specialize the class itself before specializing its members. So

template <class X, int N>
struct Bar {
    Bar();
};
template<class X>
struct Bar<X,2> {
    Bar();
};
template<class X>
Bar<X,2>::Bar( ) 
{ //error gone
}

And you may further specialize your constructor as:

template<>
Bar<int,2>::Bar( ) 
{ //error gone
}

Upvotes: 0

jrok
jrok

Reputation: 55395

For partial specializations, you need to first define the specialization of the class template itself before you can go defining its members:

template <class X, int N>
struct Bar {
    Bar();
};

template<class X>
struct Bar<X,2> {
    Bar();
};

template <class X>
Bar<X,2>::Bar( ) { }

The correct form for the first one that you said it works is:

template<int N>
struct Foo {
    Foo( );
};

template<>
Foo<2>::Foo( ) { //works
}

Upvotes: 4

Related Questions