使用一个stringstream函数参数接受多个类型

Accept multiple types using one stringstream function parameter

本文关键字:参数 类型 函数 一个 stringstream      更新时间:2023-10-16

我需要实现自己的流类错误书写像cout。这里我要做的是创建一个单独的类并重载<<操作符来接受任何基本数据类型。简单的想法是一样的。但是这个程序没有编译。

错误error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const wchar_t [20]' (or there is no acceptable conversion)

#include <iostream>
#include <string> 
#include <sstream>
class ErrorWriter
{
public:
std::wstringstream& ErrorWriter::operator<<(std::wstringstream& ss){
        //write to file
      //write to console
        return ss;
    }
};
int main(){
  ErrorWriter eout;
  eout << L"this is first error";
  eout << L"nThis second error" << 1 << 2.5 << true;
}

所以我的问题

  1. 如何使用一个函数参数接受所有基本类型参数(我不需要为每个数据类型编写多个操作重载器)
  2. 其他流如cout, stringstream如何实现这个
  3. wstringstream可以由wchar_t

    构造

    std::wstringstream ss(L"this is first error");

那么为什么它不能动态地转换为wstringstream (by作为转换构造函数)

  1. 不要认为有什么明显的方法可以做到这一点

  2. 接受字符串的basic_stringstream构造函数被声明为explicit -因此转换不会自动发生

如果您的目标只是拥有一个可以接受任意参数的写入器(使用std::ostream进行转换),那么像这样的东西就可以工作了。

class ErrorWriter
{
public:
  // Omit constructor and file_log initialization
  template<typename T>
  ErrorWriter& operator<<(const T& item) {
    file_log << item;
    std::cout << item;
    return *this;
  }
private:
  std::ofstream file_log;
};