Re: Partial Template Specialization
From: Andrey Tarasevich (andreytarasevich_at_hotmail.com)
Date: 11/09/03
- Next message: Andrey Tarasevich: "Re: Partial Template Specialization"
- Previous message: Victor Bazarov: "Re: static classvariable"
- In reply to: Agent Mulder: "Partial Template Specialization"
- Next in thread: Andrey Tarasevich: "Re: Partial Template Specialization"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sun, 09 Nov 2003 08:16:26 -0800
Agent Mulder wrote:
> ...
> I have a problem with partial template specialization. In the code
> below I have a template struct Music with one method, play(),
> and three kinds of music, Jazz, Funk and Bach. When I specialize
> Music<Bach>, I expect that the original play() method is available
> in the specialization, but it is not. How can I fix this?
> ...
> struct Jazz{};
> struct Funk{};
> struct Bach{};
> template<struct A>struct Music{void play(){}};
> struct Music<Bach>{}; //partial template specialization
This is not partial specialization. This is explicit specialization. And
the correct syntax is a s follows
template<> struct Music<Bach> {};
> int main()
> {
> Music<Jazz>().play(); //OK
> Music<Funk>().play(); //OK
> Music<Bach>().play(); //error, Music<Bach>().play not declared
> return 0;
> }
> ...
Explicit (or partial) specialization of a template is an independently
defined template. You defined it as a template class with no explicit
members. That's what you get when you instantiate the specialized
version - a class with no explicit members. It doesn't have method
'play()', hence the error.
If you want to have an explicit specialization of the entire
'Music<Bach>' and still have method 'play' in it, you have no other
choice but to declare and define this method in 'Music<Bach>' explicitly.
template<> struct Music<Bach> { void play( /* whatever */ ); };
On the other hand, if you just want to explicitly specialize the method
'play' for each kind of music, there is no need to explicitly specialize
the entire template 'Music'
struct Jazz {};
struct Funk {};
struct Bach {};
template<struct A> struct Music { void play(){} };
// Explicit specializations for method 'play()'
template<> void Music<Jazz>::play() { /* whatever 1 */ }
template<> void Music<Funk>::play() { /* whatever 2 */ }
template<> void Music<Bach>::play() { /* whatever 3 */ }
-- Best regards, Andrey Tarasevich
- Next message: Andrey Tarasevich: "Re: Partial Template Specialization"
- Previous message: Victor Bazarov: "Re: static classvariable"
- In reply to: Agent Mulder: "Partial Template Specialization"
- Next in thread: Andrey Tarasevich: "Re: Partial Template Specialization"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|