2012-06-19 44 views
0

我有一個模板類中,稱爲Cell,這裏的定義:調用模板基類的轉換運算符的派生類

template <class T> 
class OneCell 
{ 
..... 
} 

我有一個轉換運算符從Cell到T,這裏

virtual operator const T() const 
{ 
    ..... 
} 

我現在已經派生類,叫做DCell,這裏

template <class T> 
class DCell : public Cell<T> 
{ 
..... 
} 

我需要重寫Cell的轉換運算符(插入一點if),但需要調用Cell的轉換運算符後。在其他的方法它應該像

virtual operator const T() const 
{ 
    if (...) 
    { 
     return Cell<T>::operator const T; 
    } 
    else throw ... 
} 

,但我得到一個編譯器錯誤

error: argument of type 'const int (Cell::)()const' does not match 'const int'

我能做些什麼?

謝謝你,對我那可憐的英語感到抱歉。

+0

我你已經把整個代碼,這將是更好 –

回答

2

你不是實際調用操作:

return Cell<T>::operator const T(); 

全碼:

template <class T> 
class OneCell 
{ 
public: 
    virtual operator const T() const 
{ 
     return T(); 
    } 
}; 

template <class T> 
class DCell : public OneCell<T> 
{ 
public: 
    virtual operator const T() const 
    { 
     cout << "operator called"; 
     return OneCell<T>::operator const T(); 
    } 
}; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    DCell<int> x; 
    int y = (int)x; 
} 
0

不要讓操作員虛擬。而是委託給protected virtual輔助函數。

template <class T> 
class Cell 
{ 
    public: 
     operator const T() const { return cvt_T(); } 
    protected: 
     virtual const T cvt_T() const; 
}; 

template <class T> 
class DCell : public Cell<T> 
{ 
    const T cvt_T() const 
    { 
     if (...) 
     { 
      return Cell<T>::cvt_T(); 
     } 
     else throw ... 
    } 
}; 

這個和其他良好的做法可以從GotW,here is the section on virtual architecture瞭解到。

+0

什麼是你的代碼的虛擬? –

+0

@KerrekSB我假設'cvt_T'應該是。 –

+0

@ Kerrek,Luchian:謝謝你指出。 Luchian是對的。 –

3

你缺少括號,所以編譯器以爲你試圖返回的成員函數,不能調用它。

 return Cell<T>::operator const T(); 
1

考慮這個代碼的CellDCell的實現:

#include <iostream> 
#include <exception> 

template<class T> 
class Cell 
{ 
protected: 
    T cnt; 
public: 
    Cell(const T& cnt = T()) : cnt(cnt){} 
    virtual operator const T() const { return cnt; } 
}; 

bool test_bool = true; 

template<class T> 
class DCell : public Cell<T> 
{ 
public: 
    DCell(const T& cnt = T()) : Cell<T>(cnt){} 
    virtual operator const T() const 
    { 
     if(test_bool) 
     { 
      return Cell<T>::operator const T(); // Here you had Cell<T>::operator const T; 
     } else { 
      throw std::exception(); 
     } 
    } 
}; 

int main() 
{ 
    DCell<int> cell(5); 
    std::cout << static_cast<int>(cell) << "\n"; // prints 5 (and a new line) 
    return 0; 
}