[英]why did it compile errorly when i added a reference argument to a member function which is the argument to std::mem_fun()?
首先,我有一個片段如下:
struct D
{
int sum;
D():sum(0){accum();}
void incre(int arg){sum+=arg;}
void accum()
{
int arr[]={1,2,3,4,5};
std::for_each(arr,arr+ sizeof(arr)/sizeof(int),
std::bind1st(std::mem_fun(&D::incre),this));
cout << sum <<endl;
}
};
int main()
{
D();
}
據我改變成員函數編譯后properly.But incre
來
void incre(int & arg){sum+=arg;}
它產生了錯誤,比如
typename _Operation::result_type std::binder1st<_Operation>::operator()
(typename _Operation::second_argument_type&) const [with _Operation =
std::mem_fun1_t<void, D, int&>]’ cannot be overloaded
你有什么想法發生了什么? 我會感激任何幫助。
發生的事情是bind1st和mem_fun 不能與所有平台上的引用一起使用 。
你可以將它與boost :: bind一起使用
std::for_each( arr, arr + sizeof(arr)/sizeof(int),
boost::bind( &D::incre, this, _1 ) );
並且看起來GNU已經確定以上是一個足夠好的解決方法來將錯誤標記為“無法修復”。
在您的情況下,您可以通過值傳入。 您也可以愉快地將指針傳遞給這些函數。
順便說一句,你在做什么應該工作。
按值傳遞可能無法修復它,因為您正在調用非const成員函數。 關於非const成員函數也存在問題。
你的另一種選擇當然是使用std :: accumulate而不是std :: for_each,這適用於你正在運行你的集合生成某些東西的特殊情況。 我通常喜歡使用累積的方式是:
Result r;
Result* binaryfunc( Result*, T value ); // returns the same pointer passed in
std::accumulate( coll.begin(), coll.end(), binaryfunc, &r );
這避免了在每次迭代時復制“結果”。 這里不需要使用bind1st或mem_fun,因此如果您通過引用傳遞值,則不會出現問題。
問題是在內部,mem_fun嘗試將其作為參數類型設置為成員函數的參數類型的const引用。 如果你使函數接受引用,那么它會嘗試創建對引用的引用,這在C ++中是非法的。 這是庫中的已知缺陷,並且正在通過將出現在C ++ 0x中的新綁定函數進行補救。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.