c++ - 派生 istringstream 并实现运算符>>(string&)

标签 c++ templates inheritance multiple-inheritance

我正在处理以下情况: 我正在使用 istringstream 的运算符 >> 在模板函数中提取格式化数据。 除了使用有空间的 std::string 调用函数时,一切都很好。 例如std::string tmp("bla tmp"); 众所周知,有一个运算符>>(不是 istringstream 的成员),它接受 istream 和字符串并使用空格作为分隔符提取数据。 所以我得到以下“bla”而不是“bla tmp”。 简而言之,我尝试变得成熟并做了以下事情:

class MyClass : public istringstream{
public:
      MyClass(const char* st) : istringstream(st){}
      void operator>>(string& st){st = this->str();}
}

但现在我面临这个问题:

MyClass my("bla tmp");
string tmp;
my >> tmp; // now tmp == "bla temp" and this is exactly what I wanted
//but this does not work
int kk;
my >> kk; //gives me "no match for operator>>"

怎么可能?! istringstream 从 istream 继承基本类型的运算符>>,而我从 istringstream 继承。 但是通过实现我自己的运算符>>并通过扩展 istringstream 结果 MyClass 失去了基本类型的运算符>>。

最佳答案

How can it be ?! istringstream inherits operator>> for basic type from istream and I inherit from istringstream.

您的运算符>>重载隐藏了基类中的运算符。您应该使用 using 声明来使基类中的 operator >> 重载参与重载决策:

class MyClass : public std::istringstream {
public:
    using std::istringstream::operator >>;
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    MyClass(const char* st) : std::istringstream(st){}
    void operator>>(std::string& st){st = this->str();}
};

名称隐藏的概念及其如何干扰重载解析在 this article by Herb Sutter 中进行了解释。 (虽然本文主要是关于虚拟函数的,但它确实讨论了您面临的完全相同的问题)。

最后,这是一个live example使用上述更改编译的代码。

关于c++ - 派生 istringstream 并实现运算符>>(string&),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16723802/

相关文章:

c++ - 确定是否通过临时

c++ - ID 字段在自定义点类中间歇性丢失

C++ 转换为派生指针或设计错误

c++ - 使用继承类作为映射值

c++ - 引用另一个类来实例化类时出现问题

C++ Linux : Declaring an array in a class causes segmentation fault

c++ - C++ 模板是否可以针对改进代码的条件执行此操作?

c++ - 通用 `Is_enabled` SFINAE 结构

c++ - 检测编译时文字和常量

ruby-on-rails - 如何通过抽象事件记录向子类类添加范围