使用一个stringstream函数参数接受多个类型
Accept multiple types using one stringstream function parameter
我需要实现自己的流类错误书写像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;
}
所以我的问题
- 如何使用一个函数参数接受所有基本类型参数(我不需要为每个数据类型编写多个操作重载器)
- 其他流如
cout
,stringstream
如何实现这个 wstringstream可以由
构造wchar_t
std::wstringstream ss(L"this is first error");
那么为什么它不能动态地转换为wstringstream (by作为转换构造函数)
-
不要认为有什么明显的方法可以做到这一点
-
接受字符串的
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;
};
相关文章:
- 扩展C++生成的代码的模板参数类型名称
- 如何在 c++ 中定义接受不同参数类型的函数向量?
- 在 C++ 中运行时调用模板时,是否可以切换模板的参数类型?
- 将函数参数类型声明为 auto
- 将函数的参数 - 签名从使用 'std::function<T>' 转换为模板参数类型
- 在 C++17 中调用具有不同参数类型的构造函数
- 具有先前参数类型匹配的参数包
- 我想知道为什么"std::unique_ptr<int> foo(新 int)"是合法的,因为"std::<int>unique_ptr"要求输入参数类型应该是"int"?
- 将可变参数类型列表的扩展打包为复杂类型的初始值设定项列表 - 合法吗?
- MSVC 错误:4 个重载中的任何一个都无法转换所有参数类型
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 如何从第一个参数推断第二个参数类型?
- C++模板函数中,指定回调函子/lambda 的参数类型,同时仍允许内联?
- 如何用不同的参数类型和数字回调函数
- C++stoi:这两个重载都无法转换所有参数类型
- 为什么std::{container}::template不能推导其参数类型
- 为模板参数类型中的新对象分配内存
- 为指向成员模板参数的指针推导额外模板参数类型的紧凑方式
- 使用std::conditional中的模板来确定函数参数类型
- C++中的短参数类型