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

时间:2018-10-27 17:53:54

标签: c++ stringstream

我正在寻找一个打印输出的函数,该函数同时接受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的内容作为参数。如何定义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.

1 个答案:

答案 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<<添加任意数量的重载以获得所需的行为。