C++:如何创建一个接受连接字符串作为参数的函数?

2023-11-24

我可以以某种方式设计我的日志记录功能,使其接受使用 C++ 的以下形式的串联字符串吗?

int i = 1;
customLoggFunction("My Integer i = " << i << ".");

.

customLoggFunction( [...] ){
    [...]
    std::cout << "Debug Message: " << myLoggMessage << std::endl << std::endl
}

Edit:

使用 std::string 作为函数的属性适用于连接字符串,但传递的非连接字符串(如 customLoggFunction("example string"))会产生编译时错误,表明该函数不适用于 char[]。当我按以下方式重载该函数时......

customLoggFunction(std::string message){...}
customLoggFunction(char message[]){...}

...串联的字符串开始工作。

我上传了代码:http://coliru.stacked-crooked.com/a/d64dc90add3e59ed


除非您求助于宏,否则不可能按照您要求的确切语法进行操作。

但如果你不介意更换<< with ,,那么你可以执行以下操作:

#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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++:如何创建一个接受连接字符串作为参数的函数? 的相关文章

随机推荐