如何将部分流作为参数传递

How to pass a partial stream as an argument?

本文关键字:参数传递 分流      更新时间:2023-10-16

我想制作一个打印输出的函数,它接受std::stringstreamstd::string,使其像一样工作

int an_int = 123;
my_print("this is an int variable I want to print " << an_int);
my_print("but I also want to be able to print strings"); 
//expected output:
>>> this is an int variable I want to print 123
>>> but I also want to be able to print string

到目前为止,我为my_print、的第二次调用尝试了什么

void my_print(std::string msg) {
std::cout << msg << std::endl;
}

但我无法计算出我需要写的超负荷才能使第一行正常工作。我认为采用std::stringstream&std::ostream&可能可行,但编译器无法推断"this is an [..]" << an_int是一个ostream:

void my_print(std::string msg);
void my_print(std::ostringstream msg)
{
my_print(msg.str());
}
//later
int an_int = 123;
my_print("this is an int variable I want to print " << an_int);

无法使用进行编译

error C2784: 'std::basic_ostream<_Elem,_Traits> &std::operator 
<<(std::basic_ostream<_Elem,_Traits> &,const char *)' : could not deduce
template argument for 'std::basic_ostream<_Elem,_Traits> &' from 'const char [20]'

我不确定我是在尝试做不可能的事情,还是语法错误。

如何将可能传递给std::cout的内容作为参数传递给write函数。我如何定义my_print(),使类似的东西输出以下

my_print("Your name is " << your_name_string);
//outputs: Your name is John Smith
my_print(age_int << " years ago you were born in " << city_of_birth_string);
//outputs: 70 years ago you were born in Citysville.

为什么不追随std::cout的脚步,制作自己的包装器呢。有点像。

#include <iostream>
struct my_print_impl {
template <typename T>
my_print_impl& operator<<(const T& t) {
std::cout << t;
return *this;
}
};
inline my_print_impl my_print; //extern if c++17 is not available
int main() {
my_print << "This is an int I want to print " << 5;
}

operator<<添加任意数量的重载,以获得您想要的行为。