简体   繁体   中英

Cannot use std::ptr_fun with function that takes reference

No C++11 or Boost allowed.

I am trying to get the following code to compile but I'm having problems. std::ptr_fun doesn't seem to like parameters that are references.

#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 error message: error C2535: 'Something std::binder2nd>::operator ()(const Something &) const' : member function already defined or declared

But if I change the parameter in Function to T x it works!

Is there any way to get this working conveniently without modifying Function ?

Live examples:

http://ideone.com/Eno7gF

http://ideone.com/kGmv7r

You cannot do this. It is a fundamental limitation to std::bind1st and std::bind2nd. The problem is that it defines two () operators, and one of them already has const & on it. So the compiler sees two identical functions. It won't be fixed since C++11 has already deprecated these methods.

See also:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM