gpt4 book ai didi

c++ - 如何将部分流作为参数传递?

转载 作者:行者123 更新时间:2023-11-28 01:27:47 24 4
gpt4 key购买 nike

<分区>

我正在寻找一个函数来打印输出,它接受 std::stringstream和一个 std::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 的内容?作为论据。我如何定义 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.

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com