我可以使用C++来设计我的日志函数,让它接受以下形式的连接字符串吗?
int i = 1;
customLoggFunction("My Integer i = " << i << ".");
。
customLoggFunction( [...] ){
[...]
std::cout << "Debug Message: " << myLoggMessage << std::endl << std::endl
}
编辑:
使用std::string作为函数的属性对连接的字符串有效,但随后传递的非连接字符串(如customLoggFunction("example string") )会产生编译时错误,指出函数不适用于char[]。当我以下面的方式重载函数时...
customLoggFunction(std::string message){...}
customLoggFunction(char message[]){...}
..。连接在一起的字符串被捕获后才能工作。
发布于 2018-06-10 01:42:11
除非借助于宏,否则不可能使用您要求的确切语法。
但是如果您不介意用,
替换<<
,那么您可以执行以下操作:
#include <iostream>
#include <string>
#include <sstream>
void log_impl(const std::string &str)
{
std::cout << str;
}
template <typename ...P> void log(const P &... params)
{
std::stringstream stream;
(stream << ... << params);
// If you don't have C++17, use following instead of the above line:
// using dummy_array = int[];
// dummy_array{(void(stream << params), 0)..., 0};
log_impl(stream.str());
}
int main()
{
log("1", 2, '3'); // prints 123
}
发布于 2018-06-10 01:47:44
对于琐碎的项目,这是我使用MACRO
做的为数不多的事情之一。你可以这样做:
#define LOG(m) do{ std::cout << timestamp() << ": " << m << '\n'; }while(0)
// ...
LOG("error: [" << errno "] " << filename << " does not exist.");
一般来说,应该避免使用MACROS
,但没有其他方法可以通过标准函数精确地实现这一点。所以..。
注意:空条件do{...}while(0)
使您能够将MACRO
放在MACRO
包含多个语句时通常不能到达的位置。
发布于 2018-06-10 15:45:04
你可以通过定义一个新的operator<<来实现。根据模糊的记忆,使用这三个签名实现函数将会起到作用:
std::string operator<<(const char * a, const std::string & b);
std::string operator<<(const std::string & a, const char * b);
std::string operator<<(const std::string & a, const std::string & b);
它们中的每一个都必须连接其参数并返回std::string。
然而,这感觉是错误的。这违背了C++的原则。我建议一种更像C++的解决方案,即将日志记录器变成一个类,并为该类编写operator<<()成员,这样您就可以运行
customLog << "My Integer i = " << i << "." << "\n";
https://stackoverflow.com/questions/50776877
复制相似问题