正在获取ostream模板以打印指针列表中的实例属性

Getting ostream template to print instance attributes in list of pointers

本文关键字:列表 指针 属性 实例 打印 获取 ostream      更新时间:2023-10-16

我正在尝试使用一个模板函数来打印列表中指向的对象的属性。

class SomeClass {
  public:
   double myVal;
   int myID;
}
std::list< boost::shared_ptr< SomeClass > > myListOfPtrs;
for ( int i = 0; i < 10; i++ ) {
  boost::shared_ptr< SomeClass > classPtr( new SomeClass );
  myListOfPtrs.push_back( classPtr );
}
template < typename T > void printList ( const std::list< T > &listRef ) {
  if ( listRef.empty() ) {
    cout << "List empty.";
  } else {
    std::ostream_iterator< T > output( cout, " " ); // How to reference myVal near here?
    std::copy( listRef.begin(), listRef.end(), output ); 
  }
}
printList( myListOfPtrs );

打印的是指针地址。我知道我通常会做类似(*itr)->myVal的事情,但我不清楚如何调整模板函数。

首先,这里不要使用shared_ptr。您的代码没有给我们任何使用内存管理的理由:

std::list<SomeClass> myListofPtrs;

然后,您需要为您的类提供自己的流插入运算符的实现:

std::ostream& operator <<(std::ostream& os, SomeClass const& obj)
{
    return os << obj.myVal;
}

如果你必须使用指针,那么你可以创建自己的循环:

for (auto a : myListOfPtrs)
{
    std::cout << (*a).myVal << " ";
}