在模板函数中打印任何结构

Joo*_*Joo 4 c++ templates struct

我有 3 个或更多 struct ,我希望我有一个函数来打印任何结构

例如 :

struct A 
{
  int a0;
  string a1;
  bool a2;
}
Run Code Online (Sandbox Code Playgroud)

struct B
{
 CString b0;
 double b1;
 int b2;
 string b3
}
Run Code Online (Sandbox Code Playgroud)

我想用相同的功能打印这个结构(A 和 B)

像这样 :

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

任何机构帮助我?

Sta*_*irl 5

C++ 中的通常做法是operator<<(std::ostream &, const T &)为您的类型定义:

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

这应该为您想要打印的每种类型完成,并且该函数应该在与该类型相同的命名空间中定义。

之后,您的数据类型可以打印到所有输出流。这也允许boost::lexical_cast使用您的类型,因为它在std::stringstream内部打印值。