问题描述
我试图重载运算符“
struct Log
{
std::string outString;
template<typename T>
friend Log& operator<<(Log& log,const T& t)
{
std::stringstream temp;
temp << t;
std::string str = temp.str();
log.outString += str;
if(str == "endl" || str == "\n")
{
//end of line -> pass string to custom print function
}
return log;
}
};
log.outString += str;
应该这样称呼。
log << "blub: " << 123 << "endl";
解决方法
您正在比较语句if(t == "endl" || t== "\n")
中的整数,将其替换为if(str == "endl" || str == "\n")
。
这是完整的代码:
#include <iostream>
#include <string>
#include <sstream>
struct Logg
{
std::string outString;
template<typename T>
friend Logg& operator<<(Logg& logg,const T& t)
{
std::stringstream temp;
temp << t;
std::string str = temp.str();
logg.outString += str;
if(str == "endl" || str == "\n")
{
//end of line -> pass string to custom print function
}
return logg;
}
};
int main()
{
struct Logg logg;
logg << "blub: " << 123 << "endl";
std::cout << logg.outString << std::endl;
return 0;
}