C ++:如何创建一个接受串联字符串作为参数的函数? [英] C++: How can i create a function that accepts concatenated strings as parameter?

查看:69
本文介绍了C ++:如何创建一个接受串联字符串作为参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can i design my logging-function in a way, that it accepts concatenated strings of the following form using C++?

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

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

编辑:

使用std :: string作为函数的属性可用于级联字符串,但是随后传递的非级联字符串(例如customLoggFunction( example string))将产生编译时错误,指出该函数不适用于char []。当我以以下方式重载函数时...

Using std::string as the attribute to the function works for the concatenated string, but then a passed non-concatenated string like customLoggFunction("example string") produces a compile-time error saying the function is not applicable for char[]. When i overload the function in the following way...

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

...连接的字符串抓紧工作。

... the concatenated strings seize to work.

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

推荐答案

这是不可能的

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

But if you don't mind replacing << with ,, then you can do following:

#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
}

这篇关于C ++:如何创建一个接受串联字符串作为参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆