c ++将不同类型连接成函数的字符串

Ton*_*ony 5 c++ string log4cpp

我的应用程序的不同部分调用记录器功能来记录详细信息.

记录器类

std::string filename = "blahblah"; // variable to store the location of the properties file 
log4cpp::PropertyConfigurator::configure(filename);

void Logger::logging(const std::string& msg)
{
   Log4cpp::Category& myLogger = log4cpp::Category::getRoot();

   myLogger.log(log4cpp::Priority::INFO, msg);//only takes in string as input
}
Run Code Online (Sandbox Code Playgroud)

打电话给上课

Logger logMe;

int a = 5;
double b = 6;

logMe.logging("log this msg" + a + "," + b);
Run Code Online (Sandbox Code Playgroud)

我意识到上面会给我错误,因为ab有不同的类型.解决它的一种方法是使用std::to_string

logMe.logging("log this msg" + std::to_string(a) + "," + std::to_string(b));
Run Code Online (Sandbox Code Playgroud)

但是,我有几百次调用日志功能,编辑每次调用都很费时间std::to_string.是否有更简单的方法来做到这一点?

哦,并澄清,代码之前的工作方式是通过定义#define函数.

#Define logging(FLAG, X)\
do {\
    ...
    clog << x; \
}while(0)

logging(LogFlag::Warning, "log this msg" << a << "," << b << endl);
Run Code Online (Sandbox Code Playgroud)

但我现在正在重写部分代码以符合静态测试.

提前致谢.

Cal*_*eth 5

您可以添加一个logging带有参数包的重载,并使用它将其连接成一个字符串std::stringstream

在c ++ 17中,我们可以使用折叠表达式,例如

template <typename Args ...>
void Logger::logging(Args ... args)
{
   std::stringstream ss;
   (ss << ... << args); 

   Log4cpp::Category& myLogger = log4cpp::Category::getRoot();

   myLogger.log(log4cpp::Priority::INFO, ss.str());
}
Run Code Online (Sandbox Code Playgroud)

在c ++ 11或14中,我们必须稍微有些棘手

template <typename ... Args >
void Logger::logging(Args ... args)
{
   std::stringstream ss;
   std::initializer_list<int> unused{ (ss << args, 0)... };

   Log4cpp::Category& myLogger = log4cpp::Category::getRoot();

   myLogger.log(log4cpp::Priority::INFO, ss.str());
}
Run Code Online (Sandbox Code Playgroud)

然后你打电话给例如

logMe.logging("log this msg", a, ",", b);
Run Code Online (Sandbox Code Playgroud)