正在获取ostream模板以打印指针列表中的实例属性
Getting ostream template to print instance attributes in list of pointers
我正在尝试使用一个模板函数来打印列表中指向的对象的属性。
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 << " ";
}
相关文章:
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 处理从列表中删除指向对象的指针的"healthy"方法是什么?
- 编译包含指向模板函数的指针的初始值设定项列表时,gcc 出错,但 clang 不出错
- 如果函数采用指向类的指针,则函数将完全脱离候选列表
- 如何将共享指针列表传递到pybind11中的c++对象
- Unique_ptr:在列表中放置时未分配释放的指针
- C++:如何初始化包含具有给定键的指针列表的映射
- 使用继承的指针列表复制构造函数或重载运算符=
- 什么是结构开头的函数列表指针,称为 c++
- 使用 c++ 的 STL 列表 ..在传递列表指针的数组中
- 静止图像::获取设备列表指针
- 列表指针类的输出向量
- 使用PThreads访问全局列表-指针问题
- 操作迭代器列表+指针
- 在c++中分配带有列表指针值的STD映射
- python链接列表指针和大小
- 如何调整STL列表指针的大小