2012-06-19 104 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; 
}