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