D
D
Door2013-06-15 16:06:04
C++ / C#
Door, 2013-06-15 16:06:04

std::bind. Bind to member data?

I wanted to try a beautiful and powerful std::bind(more precisely std::tr1::bind, you still need to work with the old standard, the Windows platform, msvc10), which, in comparison std::bind1stand std::bind2nd, among other things, solves the problem of linking to a link ... and you need to wean yourself from old binders.
I liked the fact that with the help std::bindyou can reach some data member, i.e., for example:

struct Data
{
  int d1;
  double d2;
  // ...
};

using namespace std::placeholders;
// по сути, мы создали функцию, которая принимает экземпляр Data и возвращает значение Data::d2
std::bind(&Data::d2, _1);

// т.е.
Data myData = { 1, 10.0 };
// value == 10.0
double value = std::bind(&Data::d2, _1)(myData);

Thus, let's say we need to find a container element (which contains instances of Data) whose d2 value is equal to some value. So, with the help of std::bind2nd:
struct MyPredicate
  : std::binary_function<Data, double, bool>
{
  bool operator()(Data d, double value) const
  {
    return (d.d2 == value);
  }
};

// ...
enum { SIZE = 10 };
Data arr[SIZE] = {};

const Data* const begin = arr;
const Data* const end = arr + SIZE;

double value = 0.0;
const Data* const pos = std::find_if(begin, end, std::bind2nd(MyPredicate(), value));
// ...

But with the help of the aforementioned possibility std::bind-a, all this can be made easier, it would seem:
const Data* const pos = std::find_if(begin, end,
  std::bind(std::equal_to<double>(), std::bind(&Data::d2, _1), value));

but, judging by the compiler warnings, it std::bindreturns the address of a local variable somewhere and &Data::d2an invalid pointer is passed instead.
So, I would like to know, maybe the correct implementation of this, or I’m completely alien and no one needs it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
ixSci, 2013-06-16
@ixSci

About bind and msvc: it's very badly written and contains a lot of bugs, so you may not be surprised by its strange behavior in the studios (including 2012)

I am a complete stranger and no one needs it.

That's right, std::bind has become obsolete before it became a full-fledged part of the standard. Use lambdas.

M
Mephi1984, 2013-06-17
@Mephi1984

You can get objects by reference. To do this, you can use std::ref and std::cref
en.cppreference.com/w/cpp/utility/functional/ref
Write if it helps or doesn't help. My compiler is far away, but when I get home, I can check in more detail.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question