0

I'm looking to make a function to print output, that accepts both a std::stringstream and a std::string to make it work like

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

What I've tried so far for the second call of my_print,

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

but I can't figure out the overload I need to write to make the first line work. I thought taking a std::stringstream&, or an std::ostream&, might work, but the compiler can't deduce that "this is an [..]" << an_int is an 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);

fails to compile with:

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]'

I'm not sure whether I'm trying to do the impossible, or if my syntax is wrong.

How can I pass write a function that takes what you might pass to std::cout as an argument. How can I define my_print() so that something like this outputs the following

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.
TankorSmash
  • 12,186
  • 6
  • 68
  • 106

1 Answers1

2

Why not follow in the footsteps of std::cout and make your own wrapper. Something like.

#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;
}

Add any number of overloads for operator<< to get the behaviour you are looking for.

super
  • 12,335
  • 2
  • 19
  • 29