在派生类中调用模板基类的强制转换操作符

时间:2012-06-19 21:14:46

标签: c++ templates inheritance casting virtual

我有一个模板类,名为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 ...
}

但是我遇到了编译错误

  

错误:类型'const int(Cell ::)()const'的参数与'const int'不匹配

我该怎么办?

谢谢,抱歉我的英语不好。

4 个答案:

答案 0 :(得分:3)

您缺少括号,因此编译器认为您尝试返回成员函数,而不是调用它。

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

答案 1 :(得分: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;
}

答案 2 :(得分: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;
}

答案 3 :(得分: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学习这个和其他良好实践。