2011-12-01 53 views
2

我找不到在其他地方回答的這個問題,所以我最終決定問。 我有一個C++模板類,包括鑄造操作者的一個參數的類型:鑄造操作者對模板參數的專門化

template <class E, class B> 
class bar { 
    private: 
     B innerVal_; 
    [...] 
    public: 
     /* Casting to the type of the 2nd template argument */ 
     operator B() const { return innerVal_; }; // default implementation provided 
}; 

不過,我需要爲某些特定的模板參數提供這種轉換操作符的專業化,比如:

template<> 
bar<concreteType,int>::operator int() // <-- whoops, error! 
{ [...] } 

問題是,無論我如何指定鑄造操作符的語法,gcc始終返回一個引用該函數聲明的錯誤。最常見的一種是:

error: template-id ‘operator int<>’ for ‘bar< concreteType, int>::operator int()’ does not match any template declaration.

我與這些線路有:

  • 定義轉換操作符爲 「操作INT()」
  • 使用 「運營商的TypeB()」,之後宣佈在原始模板中一行「typedef B typeB;」

我也玩過「typename」關鍵字,模板括號,並做了一些其他絕望的嘗試。所有這些都會導致奇怪的錯誤 - 我甚至不會在這裏粘貼。

我失去了一些明顯的細節?你有任何提示/指針嗎?任何幫助都是有用的。

回答

3

在C++中,您不能在類的模板參數上專門化成員函數。因此,這裏的解決辦法:

template <class E, class B> 
class bar_base { //base class with 99% of the implementation 
    private: 
     B innerVal_; 
    public: 
    [...] //most of your members here 
}; 
template <class E, class B> 
class bar : public bar_base<E,B> { //normal instantiation 
public: 
    [...] //constructors only 
    /* Casting to the type of the 2nd template argument */ 
    operator B() const { return innerVal_; }; // default implementation provided 
}; 
template <class E> 
class bar<E,int> : public bar_base<E,int> { //E,int specialization 
public: 
    [...] //constructors only 
    operator int() const { [...]}; 
}; 

,或者更簡單,現在,我認爲它:

private: 
    template<class T> 
    T convert_to() {return innerVal_; } 
    template<> 
    int convert_to<int>() {return innerVal_; } 
public: 
    operator B() const { return convert_to<B>(); }; 
+0

埃姆...謝謝大家的響應速度快,但我真的不undersand你的答案。 「部分特化」究竟意味着什麼?據我所知,我的專業化已滿: 模板<> // < - 沒有參數,完全專業 酒吧 ::運營商type2(){...} (我已經更改類型爲type1, type2,它們被認爲是真實的類型:假設type1 = type2 = int)。 另一方面,是不是有沒有涉及繼承的解決方案?謝謝。 – dunadar

+0

@dunadar:無法在類的模板參數上專門化成員函數。你必須使用繼承,或者對SFINAE很狡猾(我不這麼認爲,另外,我不確定你是否可以輕鬆地轉換SFINAE操作符,我會考慮它) –

+0

@dunadar:我明白了我的意思你所要做的就是將這個函數變成一個_template_函數,並且一切都很好,很棒。答案已更新。 –