首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C++:如何创建一个接受连接字符串作为参数的函数?

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

Stack Overflow用户
提问于 2018-06-10 01:33:30
回答 4查看 342关注 0票数 6

我可以使用C++来设计我的日志函数,让它接受以下形式的连接字符串吗?

代码语言:javascript
复制
int i = 1;
customLoggFunction("My Integer i = " << i << ".");

代码语言:javascript
复制
customLoggFunction( [...] ){
    [...]
    std::cout << "Debug Message: " << myLoggMessage << std::endl << std::endl
}

编辑:

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

代码语言:javascript
复制
customLoggFunction(std::string message){...}
customLoggFunction(char message[]){...}

..。连接在一起的字符串被捕获后才能工作。

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

EN

回答 4

Stack Overflow用户

发布于 2018-06-10 01:42:11

除非借助于宏,否则不可能使用您要求的确切语法。

但是如果您不介意用,替换<<,那么您可以执行以下操作:

代码语言:javascript
复制
#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
}
票数 7
EN

Stack Overflow用户

发布于 2018-06-10 01:47:44

对于琐碎的项目,这是我使用MACRO做的为数不多的事情之一。你可以这样做:

代码语言:javascript
复制
#define LOG(m) do{ std::cout << timestamp() << ": " << m << '\n'; }while(0)

// ...

LOG("error: [" << errno "] " << filename << " does not exist.");

一般来说,应该避免使用MACROS,但没有其他方法可以通过标准函数精确地实现这一点。所以..。

注意:空条件do{...}while(0)使您能够将MACRO放在MACRO包含多个语句时通常不能到达的位置。

票数 4
EN

Stack Overflow用户

发布于 2018-06-10 15:45:04

你可以通过定义一个新的operator<<来实现。根据模糊的记忆,使用这三个签名实现函数将会起到作用:

代码语言:javascript
复制
std::string operator<<(const char * a, const std::string & b);
std::string operator<<(const std::string & a, const char * b);
std::string operator<<(const std::string & a, const std::string & b);

它们中的每一个都必须连接其参数并返回std::string。

然而,这感觉是错误的。这违背了C++的原则。我建议一种更像C++的解决方案,即将日志记录器变成一个类,并为该类编写operator<<()成员,这样您就可以运行

代码语言:javascript
复制
customLog << "My Integer i = " << i << "." << "\n";
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50776877

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档