This cites for_each as follows:
template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f);
I have a collection std::list<std::string>, and a function void Do(std::string) works fine when given to for_each along with the iterators. But if I supply a function like void Do(std::string&), it does not compile. Is there a way around it? Or should I forget about it as some RVO like magic is going on? 😀
EDIT:
bool PluginLoader::LoadSharedObjects()
{
for_each(l_FileNames.begin(), l_FileNames.end(), bind1st(mem_fun(&PluginLoader::LoadSharedObject),this));
}
void PluginLoader::LoadSharedObject(const std::string sFileName)
{
void* pHandle = dlopen(sFileName.c_str(), i_LibMode);
//if(pHandle == NULL)
//Check dlerror
//Add handle to list
}
Code added. I woul like LoadSharedObject function to be of the form void PluginLoader::LoadSharedObject(const std::string& sFileName) if it is possible.
The error is not with for_each but with bind1st and mem_fun. They simply dont’t support what you’re trying to do. They cannot handle functions which take reference parameters. You could write your own functor, use boost::bind or wait until you’re able to use C++0x lambdas.
Example for your own functor:
Of course, you don’t have to use std::for_each. A simple for-loop will do as well.