Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print any struct in template function

I have 3 or more struct , and I want that I have one function for print any struct

for example :

struct A 
{
  int a0;
  string a1;
  bool a2;
}

and

struct B
{
 CString b0;
 double b1;
 int b2;
 string b3
}

I want print this struct ( A and B) with same function

like this :

template<typename T>
inline void print(T)
{
  std::cout << // I don't know what is write here....
}

any body help me?

like image 394
Joo Avatar asked Feb 13 '18 13:02

Joo


1 Answers

Usual practice in C++ is to define operator<<(std::ostream &, const T &) for your type:

std::ostream &operator<<(std::ostream &os, const A &value)
{
    // print here
    return os;
}

This should be done for each type you want to print and this function should be defined in the same namespace as that type.

After that, your data types can be printed to all output stream. This also allows things like boost::lexical_cast to work with your type as it prints value to std::stringstream internally.

like image 107
StaceyGirl Avatar answered Oct 13 '22 01:10

StaceyGirl