C++ 将不同的类型连接成函数的字符串
c++ concatenate different types into a string for function
我的应用程序的不同部分调用记录器函数来记录详细信息。
记录器类
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
}
调用类
Logger logMe;
int a = 5;
double b = 6;
logMe.logging("log this msg" + a + "," + b);
我意识到以上会给我错误,因为a
和b
是不同类型的。解决它的一种方法是使用std::to_string
logMe.logging("log this msg" + std::to_string(a) + "," + std::to_string(b));
但是,我对日志记录功能有数百个调用,并且编辑对std::to_string
的每个调用都会很耗时。有没有更简单的方法可以做到这一点?
哦,澄清一下,代码之前的工作方式与之前的方式一样,是通过定义 #define 函数。
#Define logging(FLAG, X)
do {
...
clog << x;
}while(0)
logging(LogFlag::Warning, "log this msg" << a << "," << b << endl);
但是我现在正在重写部分代码以符合静态测试。
提前谢谢。
您可以使用std::stringstream
添加logging
重载,该重载采用参数包并将其联接到字符串
中在 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());
}
在 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());
}
然后你调用任何一个,例如
logMe.logging("log this msg", a, ",", b);
我建议在类中添加一个operator<<()
class Logger
{
public:
Logger &operator<<(const std::string &s)
{
logging(s)
return *this;
};
Logger &operator<<(const char *s)
{
return operator<<(std::string(s));
}
template <class T>
Logger &operator<<(const T &v)
{
std::ostringstream s;
s << v;
return operator<<(logging(ss.str()));
};
// other stuff you have in your class, including the logging() function
};
// to use
logMe << "log this msg" << a << b;
与您描述的使用它的语法不完全相同,但它更普遍地工作。
使用stringstream
相当容易。然后,您可以使用str()
将其转换为std::string
。
#include <sstream>
...
int a = 5;
double b = 6;
std::stringstream ss;
ss << "log this msg" << a << b;
std::cout << ss.str() << std::endl;
logMe.logging(ss.str());
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何从void函数输出字符串
- 使用用户定义函数的字符串反转
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- 在c++构造函数中使用随机字符串生成器
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- C++:如何使函数只返回作为列表一部分的字符串
- 如何在C++中的同一函数中使用字符串和双精度
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 一个函数,用于查找字符串1包含字符串2 c++的次数
- 对函数 PlaySound 使用字符串变量
- 具有多个模板的模板函数,用于特定数据类型(如字符串)?
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- Visual c ++,使用字符串引用/指针调用 dll 函数
- 构造函数字符串参数未设置窗口标题
- C++默认构造函数:字符串参数与字符串参数()
- 使用函数C++字符串输入
- c++模板函数字符串类型不匹配