我正在寻找一个打印输出的函数,该函数同时接受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.
答案 0 :(得分:2)
为什么不按照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<<
添加任意数量的重载以获得所需的行为。