2010-02-15 97 views
1

我想一個額外的轉換操作符添加到模板子類作爲專業化 - 即:在專業化添加一個方法

- 可以一spelcialization繼承其主模板中的所有方法的一個特例?

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()); } 
}; 

回答

4

模板專業化是不同的類型,因此不共享函數。

您可以通過公共基類繼承得到共享功能:

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(); } 
}; 
0

你也可以引入一個虛擬模板參數:

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. 

哎呀!這開始看起來很像模板元編程!請注意...