我有一个使用以下定义进行日志记录的方法:
void log(std::string s) {
std::string tag = "main";
std::cout << tag << " :" << s << std::endl;
}我试图这样称呼这个方法:
log("direction" << std::to_string(direction) << ", count: " << std::to_string(count));direction和count是整数。
在红色下划线的<<中,我得到了以下错误:
没有任何运算符<<与这些操作数匹配。操作数类型为const 10 << std::string
我的头中有#include<string>,以确保字符串能够正常工作。
我试过std::string("direction"),但问题还是一样。
C++初学者。我会感谢你的帮助。
发布于 2017-09-21 09:26:18
在您操作字符串时,使用<<操作符替换+,而不是流:
log("direction" + std::to_string(direction) + ", count: " + std::to_string(count));发布于 2017-09-21 09:26:46
operator<<不用于任意字符串连接-它被称为“输出流操作符”,并且仅在std::ostream上下文中使用。
你说..。
std::cout << tag << " :" << s << std::endl;.你实际上写的代码大致相当于:
std::cout.operator<<(tag).operator<<(" :").operator<<(s).operator<<(std::endl);如您所见,operator<<知道如何使用std::cout和std::string,但不知道如何在字符串之间工作。
为了连接std::string实例,只需使用operator+
log("direction" + std::to_string(direction) + ", count: " + std::to_string(count));请注意,这种级联技术并不是最有效的:您可能希望查看std::stringstream或简单地使用std::string::reserve来避免不必要的内存分配。
发布于 2017-09-21 09:33:01
如果您决定使用operator<<表示法,则需要一个了解它的对象。
这里有一个这样的对象(我不认为这是个好主意):
#include <string>
#include <sstream>
#include <iostream>
void log(std::string s) {
std::string tag = "main";
std::cout << tag << " :" << s << std::endl;
}
struct string_accumulator
{
std::ostringstream ss;
template<class T>
friend string_accumulator& operator<<(string_accumulator& sa, T const& value)
{
sa.ss << value;
return sa;
}
template<class T>
friend string_accumulator& operator<<(string_accumulator&& sa, T const& value)
{
return operator<<(sa, value);
}
operator std::string () { return ss.str(); }
};
inline auto collect() -> string_accumulator
{
return string_accumulator();
}
int main()
{
int direction = 1;
int count = 1;
log(collect() << "direction" << std::to_string(direction) << ", count: " << std::to_string(count));
}https://stackoverflow.com/questions/46340157
复制相似问题