tags:

views:

69

answers:

2

I want to add an additional conversion operator to a specialization of a template

-can a spelcialization inherit all methods from its main template ?

template<class T>
MyClass
{
public:
    operator Foo() { return(getAFoo()); }
};


template<>
MyClass<Bar>
{
public:
    // desire to ADD a method to a specialization yet inherit
    // all methods from the main template it specializes ???
    operator Bar() { return(getABar()); } 
};
+3  A: 

Template specializations are distinct types and thus don't share functions.

You can get shared functionality by inheriting from a common base class:

template<class T>
struct Base {
    operator Foo() { return Foo(); }
};

template<class T>
struct C : Base<T> {
    // ...
};

template<>
struct C<Bar> : Base<Bar> {
    // ...
    operator Bar() { return Bar(); }
};
Georg Fritzsche
A: 

You could also introduce a dummy template parameter:

template<class T, int i=0>
MyClass
{
public:
    operator Foo() { return(getAFoo()); }
};

typedef MyClass<Bar, 1> MyClassBarBase;

template<>
MyClass<Bar, 0>: public MyClassBarBase {
public:
    // put compatible constructors here
    // add whatever methods you like
}

//When the client instantiates MyClass<Bar>, they'll get MyClass<Bar, 0> 
//because of the default. MyClass<Bar, 0> inherits from MyClass<Bar, 1>, 
//which is the "vanilla" version the MyClass template for type Bar. You 
//only need to duplicate the constructor definitions.

Yikes! This is starting to look a lot like template metaprogramming! Please be careful...

olooney