2010-10-13 86 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 &。如此有效,這意味着您正試圖形成對參考的參考。