2010-10-13 84 views
4

This引用的for_each如下:有没有什么办法让for_each参考?

template<class InputIterator, class Function> 
    Function for_each(InputIterator first, InputIterator last, Function f); 

我有一个集合std::list<std::string>,并且在与迭代器一起给for_eachvoid Do(std::string)正常工作的功能。但是如果我提供像void Do(std::string&)这样的函数,它不会编译。有没有办法解决它?或者我应该忘记一些像魔术一样的RVO? :d

编辑:

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 
} 

代码加入。如果可能的话,我需要LoadSharedObject函数的形式为void PluginLoader::LoadSharedObject(const std::string& sFileName)

+1

请显示一些代码。 :) – 2010-10-13 07:03:49

回答

3

该错误不是for_each,而是bind1st和mem_fun。他们根本不支持你想要做的事情。他们不能处理引用参数的函数。你可以写你自己的函数,使用boost :: bind或者等到你能够使用C++ 0x lambdas。

自己的仿函数

例子:

struct LoadSharedObjFunctor 
{ 
    PluginLoader *pl; 
public: 
    explicit(PluginLoader *p) 
    : pl(p) {} 

    void operator()(std::string const& cref) const 
    { return pl->LoadSharedObject(cref); } 
}; 

... 
std::for_each(...,...,LoadSharedObjFunctor(this)); 
... 

当然,你不使用std :: for_each的。一个简单的for-loop也可以。

+0

我不能使用任何第三方库:(我不认为写我自己的一个会变得很好:)。 – nakiya 2010-10-13 07:32:57

+0

@nakiya:然后写你自己的函子。 – sellibitze 2010-10-13 07:43:52

0

目前的标准还不清楚是否允许使用for_each这样的用法,而且不同的实现的行为是不同的 - 有些可以接受但有些不可以。这被一些人认为是不幸的,所以如果迭代器是可修改的,C++ 0x将通过明确允许传递给for_each的变异操作来解决这种情况。

关于编辑:const引用不是问题。你会得到什么错误?

+0

什么时候这个虚幻的C++ 0x会出来。这些天我到处都看到它。 :D – nakiya 2010-10-13 07:10:16

+0

我不能等到它自己:DI真的希望它发生在2011年3月。引用http://www2.research.att.com/~bs/C++0xFAQ.html#when-standard:“新标准很可能被称为C++ 11,但即使是微小的延迟也可能使C++ 12成为可能。“ – usta 2010-10-13 07:19:17

+0

C++真的令人费解,不是吗?:D – nakiya 2010-10-13 07:21:12

1

如果你被允许使用提升,那么你想要的是boost:::bind

#include <boost/bind.hpp> 
... 
for_each(l_FileNames.begin(), 
     l_FileNames.end(), 
     boost::bind(&PluginLoader::LoadSharedObject, this, _1)); 

只是为了好玩,这是为什么你正在尝试不起作用:

mem_fun(&PluginLoader::LoadSharedObject)创建mem_fun1_t<void, PluginLoader, const string &>类型的对象。

因此bind1st(mem_fun(&PluginLoader::LoadSharedObject),this)创建一个binder1st< mem_fun1_t<void, PluginLoader, const string &> >类型的对象。

的问题是,binder1st定义,看起来像一个功能: ResultType operator()(const ArgType &),其中ArgTypeconst string &。如此有效,这意味着您正试图形成对参考的参考。