加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

通过函数C传递stringstream值

发布时间:2020-12-16 07:00:10 所属栏目:百科 来源:网络整理
导读:我目前有一个日志系统,它接受char *和var args,然后使用它们来执行printf.这适用于C风格的字符串,但我有点清洁.目前,如果我使用std :: stringstream,我必须在日志系统之外创建stringstream,然后将char *用于stringstream给出的字符串.它看起来像这样: std::
我目前有一个日志系统,它接受char *和var args,然后使用它们来执行printf.这适用于C风格的字符串,但我有点清洁.目前,如果我使用std :: stringstream,我必须在日志系统之外创建stringstream,然后将char *用于stringstream给出的字符串.它看起来像这样:

std::stringstream strStream;
strStream << "The value of x is: " << x;
logging::print( strStream.str().c_str() );

我想要的是将参数传递给函数,就像我直接使用字符串流一样.从用户的角度来看,这看起来像这样:

logging::printStream("The value of x is: " << x);

或者可能是这样的:

logging::printStream("The value of x is: ",x);

有没有办法以这样的方式使用日志记录,我可以使用字符串流而不必在日志系统的函数之外创建它?

这一点尤其重要,因为我打算创建一个宏来阻止任何函数参数在运输版本中进行编译.如果我必须在它之外创建字符串流并将其传入,宏将无用.从技术上讲,我可以创建一个宏来完成我在这个问题中讨论的字符串流的东西,但是这很麻烦,因为我不会总是使用字符串流与此日志记录,所以我将有一个宏用于标准日志记录,并使用不同的宏来使用其中的字符串流调用宏进行标准日志记录.

解决方法

我想出了两个HACK解决方案,但它们应该可以工作.第一个不使用范围解析运算符,更安全.第二个使用noop int变量来伪造范围.

#define logging_printStream(token) { std::stringstream o; o << token; logging::print(o.str().c_str()); }

namespace logging { int noop; }
#define printStream(token) noop = 0; { std::stringstream o; o << token; logging::print(o.str().c_str()); }

int main(int argc,const char** argv)
{
    int i = 1;

    // MORE SAFE
    logging_printStream(i)
    logging_printStream("is this magic? " << (i ? "yes" : "no"))

    // LESS SAFE
    logging::printStream(i)
    logging::printStream("is this magic? " << (i ? "yes" : "no"))
}

由于17.6.4.3.2,我将logging__printStream更新为logging_printStream

17.6.4.3.2 Global names [global.names]

Certain sets of names and function signatures are always reserved to the implementation:

  • Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.
  • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

由于3.6.1,我单独留下了主要声明

3.6.1 Main function [basic.start.main]

A program shall contain a global function called main,which is the designated start of the program. It is implementation-defined whether a program in a freestanding environment is required to define a main function. An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int,but otherwise its type is implementation-defined.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读