Ric*_*hr. 6 c++ cout stdstring
我可以用某种方式设计我的日志记录功能,它使用C++接受以下形式的串联字符串吗?
int i = 1;
customLoggFunction("My Integer i = " << i << ".");
Run Code Online (Sandbox Code Playgroud)
.
customLoggFunction( [...] ){
[...]
std::cout << "Debug Message: " << myLoggMessage << std::endl << std::endl
}
Run Code Online (Sandbox Code Playgroud)
编辑:
使用std :: string作为函数的属性适用于连接字符串,但是传递的非连接字符串(如customLoggFunction("example string"))会产生编译时错误,表示该函数不适用于char [].当我以下列方式重载函数时...
customLoggFunction(std::string message){...}
customLoggFunction(char message[]){...}
Run Code Online (Sandbox Code Playgroud)
...连接的字符串抓住了工作.
除非您使用宏,否则无法使用您要求的确切语法.
但是,如果你不介意更换<<用,,那么你可以做以下操作:
#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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
197 次 |
| 最近记录: |