C ++包装模板化函数

时间:2011-03-04 18:55:50

标签: c++ templates operator-overloading subclass

  • 我有一个模板类A,以及一个A的流操作符函数,因此是一个模板函数。
  • 我有一个继承自A的B类,指定模板的类型并添加一些特定于B的东西。
  • 我正在B上编写一个流操作符来执行特定于B的操作,然后回退到为A编程的其余流操作。

因为B是A的子类(你称它为?),调用A的流运算符应该有效。实际上,main()中的operator>>(f,a)可以正常工作。但由于某种原因,它不适用于B转换为A.我得到的错误是“没有匹配函数调用'运算符>>(std :: basic_istream>&,A)”。

我做错了什么?

以下是示例代码:

#include <stdlib.h>
#include <fstream>
#include <iostream>

using namespace std;


template <class TypeT>
class A
{
public:
    A(){a = -9;}
    A(TypeT v){a = v;}
    TypeT a;
};

class B : public A<int>
{
public:
    B(int w) : A<int>(10) {b = w;}
    int b;
};

template <class TypeT>
istream &operator>> (istream &s, A<TypeT> &a)
{
    cout << "a.a = " << a.a << endl;
    return s;
}

istream &operator>> (istream &s, B &b)
{
    cout << "b.b = " << b.b << "  ";
    operator>>( s, (A<int>)b);    // error!
    return s;
}



int main(void) {
    ifstream f("/dev/null");

    A<int> a(0);
    operator>>( f, a );

    B b(1);
    operator>>( f, b );

    return EXIT_SUCCESS;
}

2 个答案:

答案 0 :(得分:3)

将您的演员阵容更改为:

operator>>(s, (A<int> &)b);

您的原始强制转换会创建一个临时表,您只能获得const引用。

答案 1 :(得分:1)

问题在于你的C-cast显然正在创建一个新对象而不是按预期进行向上转换。由于这个新对象是临时的,因此不能将非const引用参数绑定到父的运算符函数。如果你static_cast引用了父作品,它应该有效:

operator>>( s, static_cast<A<int>&>(b));

相关问题