我正在尝试创建一个记录器功能,您可以在其中传递将记录到文本文件的消息.有时我想传入一个与我的消息连接的变量,所以我可以做类似的事情:
logger("The variable is: " + variable);
Run Code Online (Sandbox Code Playgroud)
该功能定义为
void logger(std::string message);
Run Code Online (Sandbox Code Playgroud)
我正在使用Qt,所以我不知道它是否相关,但变量将永远是QString.当我尝试这个时,它会说没有候选功能
void logger(const QString);
Run Code Online (Sandbox Code Playgroud)
所以我想为什么不做第二个功能,它会期望连接:
void logger(std::string message);
void logger2(const QString message);
Run Code Online (Sandbox Code Playgroud)
我做的时候编好了
logger2("The variable is: " + variable);
Run Code Online (Sandbox Code Playgroud)
但是,当我调试传递的消息变量时,它是一个空字符串.我如何让它工作,是否可能?
为什么不做这样的事情:
QString qs = "hello";
qs.toStdString();
Run Code Online (Sandbox Code Playgroud)
至于动态连接,我喜欢使用一个简单的格式化程序类:
class Formatter
{
public:
template<class Val> Formatter& operator<<(const Val& val)
{
ss_ << val;
return * this;
}
operator string () const { return ss_.str().c_str(); }
private:
std::stringstream ss_;
};
Run Code Online (Sandbox Code Playgroud)
......可以像这样使用:
logger(Formatter() << "The variable is: " << variable);
Run Code Online (Sandbox Code Playgroud)