2014-12-03 93 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