如何将部分流作为参数传递
How to pass a partial stream as an argument?
我想制作一个打印输出的函数,它接受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
的内容作为参数传递给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<<
添加任意数量的重载,以获得您想要的行为。
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用指向成员的指针将成员函数作为参数传递
- 如何将参数传递给正在使用模板的类
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将部分流作为参数传递
- 我正在开发服务器,ip作为参数传递不起作用
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 将参数传递为"const"的奇怪效果
- 如何在 c++ 中将函数作为参数传递?
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 使用引用与指针将数组作为参数传递
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 为什么我不能将引用作为 std::async 的函数参数传递
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将__device__ lambda 作为参数传递给 __global__ 函数