Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

what is the return type of std::bind()?

38 views
Skip to first unread message

Christof Warlich

unread,
Mar 23, 2016, 9:49:56 AM3/23/16
to
Hi,

I'm trying to understand how to use functors with std::bind().

The following code defines a simple example class named "Offset" to instantiate three different functors being used to calculate its "result" member variable in three increasingly complex scenarios:

#include <functional>
#include <iostream>

struct Offset {
Offset(int offset): offset(offset) {}
void operator()(int value) {
result = offset + value;
}
int result;
private:
int offset;
};

int main() {

// scenario 1
Offset offset10(10);
offset10(100);
std::cout << "offset10(100) yields result "
<< offset10.result
<< std::endl;

// scenario 2
std::function<void(int)> offset20(Offset(20));
offset20(100);
std::cout << "offset20(100) yields result "
<< offset20.target<Offset>()->result
<< std::endl;

// scenario 3
std::function<void()> offset100by30 = std::bind(Offset(30), 100);
offset100by30();
std::cout << "offset100by30() yields result "
//<< offset100by30.???->result
<< std::endl;

return 0;
}

My issue is with scenario 3, i.e. when using std::bind(): How could I access the result member variable in this case?

Please note that this is a contrived example to simplify things: I _do_ need a solution where Offset is passed as a temporary as shown, i.e. passing it as a reference would not be an option.

Thanks for any help,

Chris

Öö Tiib

unread,
Mar 23, 2016, 4:44:53 PM3/23/16
to
The type returned by 'std::bind' is of unspecified Callable type that is
not required to have any methods of extracting what was bound into it.

>
> Please note that this is a contrived example to simplify things: I _do_
> need a solution where Offset is passed as a temporary as shown, i.e.
> passing it as a reference would not be an option.

You assume a solution but do not describe a problem that it solves.
What is the benefit of using 'std::bind'? I felt it as sort of obsolete
with lambdas available.

Christof Warlich

unread,
Mar 24, 2016, 2:34:07 AM3/24/16
to
Am Mittwoch, 23. März 2016 21:44:53 UTC+1 schrieb Öö Tiib:
> What is the benefit of using 'std::bind'? I felt it as sort of obsolete
> with lambdas available.

You are right, using a lambda with capture by reference instead of std::bind solves my (initial) problem :-). Many thanks for your suggestion!

0 new messages