C++ 是否有方法打印当前类中复合数据类型的所有属性

C++ 是否有方法打印当前类中复合数据类型的所有属性,c++,class,templates,C++,Class,Templates,这里我有一个模板中的堆栈类 template <class T, int s> class stack { private: int size; //size of stack T array[s]; // use array to implement stack, s is an initial argument } 我可以声明一个堆栈bs在主菜单中 是否有办法使用堆栈中的函数打印所有“标题,年份”?请记住,这是一个模板,对于其他一些类来说应该是通用的,比如 class

这里我有一个模板中的堆栈类

template <class T, int s>
class stack
{
private:
  int size;  //size of stack
  T array[s]; // use array to implement stack, s is an initial argument
}
我可以声明一个
堆栈bs在主菜单中
是否有办法使用
堆栈中的函数打印所有
“标题,年份”
?请记住,这是一个模板,对于其他一些类来说应该是通用的,比如

class movie  
{
public:
  string title;
  int year;
}

提前感谢。

您应该使用迭代器等工具公开对
T
的访问,并在
电影
类中提供
print()
函数

将容器与其包含的项目紧密耦合通常是个坏主意


通过标准容器,我会使用类似的东西

 template <typename Container>
 std::ostream& operator<<(std::ostream& os, Container c) {
    for(auto x : c) {
       os << x << std::endl;
    }
    return os;
 }

当然,
templating
提供编译时多态性,这意味着您假定的
printAll
函数将与定义正确函数的任何类型一起工作,即您可以执行以下操作:

void printAll() {
    for (auto it = array.begin(); it != array.end(); ++array)
        cout << it->title << ", " << it->year << "\n";
}
现在可以使用任何支持打印功能的类型。从这里,您可以不断获得更高的级别,例如,您可以通过重载stream操作符来执行以下操作:

cout << (*it);

<代码>听起来好像你想要反射,C++没有。您的
堆栈
类没有提供所需内容的函数。您需要自己编写一个。要求堆栈中存储的每个类型都有一个关联的stream out运算符重载,然后迭代每个元素并将它们发送到流。虽然没有提供此功能,但使用构造函数(或advanced:type)打印基类(取模板参数包中的所有字段)可以创造奇迹。。。
void printAll() {
    for (auto it = array.begin(); it != array.end(); ++array)
        cout << it->title << ", " << it->year << "\n";
}
Book::print() {
    cout << "The book " << title << " is from " <<  year << "\n"
}
void printAll() {
    for (auto it = array.begin(); it != array.end(); ++array)
       it->print();
}
cout << (*it);