2014-12-03 29 views
3

不允許使用C++ 11或Boost。無法使用std :: ptr_fun和帶參考的函數

我想獲得下面的代碼來編譯,但我有問題。 std::ptr_fun似乎不喜歡參考。

#include <algorithm> 
#include <functional> 
#include <vector> 

struct Something 
{ 
}; 

template<class T> 
T Function(const T& x, int s) 
{ 
    // blah blah 
    return x; 
} 

int main() 
{ 
    std::vector<Something> data(20); 
    std::transform(data.begin(), data.end(), data.begin(), std::bind2nd(std::ptr_fun(Function<Something>), 8)); 
} 

VS2013錯誤消息: 錯誤C2535: '某物的std :: binder2nd> ::運算符()(常量東西&)常量':已經定義或聲明

但是,如果我改變成員函數參數FunctionT x它的工作原理!

有沒有辦法讓這個工作方便而不需要修改Function

活生生的實例:

http://ideone.com/Eno7gF

http://ideone.com/kGmv7r

+0

VS2013支持C++ 11庫的很大一部分,所以儘管你限制你可以訪問'STD: :綁定「和」標準::佔位符「 – Mgetz 2014-12-03 18:50:13

回答

2

你不能做到這一點。這是std :: bind1st和std :: bind2nd的一個基本限制。問題是它定義了兩個()運算符,其中一個已經有const &。所以編譯器會看到兩個相同的函數。它不會被修復,因爲C++ 11已經不推薦使用這些方法。

參見:

Using bind1st for a method that takes argument by reference

weird compiler error using bind2nd(): "member function already defined or declared" instead of "reference to reference"

Bind2nd issue with user-defined class