小编Kin*_*ead的帖子

如何编写可以处理对象或指针函数调用的模板函数?

我希望能够编写一个模板函数,可以调用容器的所有元素上的函数调用.我们可以假设函数名称始终相同.然而,未知的是容器是否保持物体或指针.即,我是否应该去引用.

template< typename TContainer >
void ProcessKeyedContainer( TContainer &keyedContainer )
{
  for ( auto it = keyedContainer.begin(); it != keyedContainer.end(); ++it )
  {
    // do some random stuff here.
    // ...

    auto value = it->second;
    value.Process(); // or value->Process() if the container has pointers
  }
}

...

std::map< int, CMyObject > containerOfObjects;
containerOfObjects[0] = CMyObject();

std::map< int, CMyObject* > containerOfPointers;
containerOfPointers[0] = new CMyObject();

// I would like both calls to look near identical
ProcessKeyedContainer( containerOfObjects ); 
ProcessKeyedContainer( containerOfPointers ); …
Run Code Online (Sandbox Code Playgroud)

c++ templates

4
推荐指数
1
解决办法
302
查看次数

标签 统计

c++ ×1

templates ×1