Why can't I create a binding?
So tell me that I want to do some functors constexpr
, although I could do it using bind
. Is there something I am missing? Why bind
can't it return constexpr
?
Given:
struct foo {
int b() const { return _b; }
int a() const { return _a; }
int r() const { return _r; }
const int _b;
const int _a;
const int _r;
};
I want to:
constexpr auto sumB = bind(plus<int>(), placeholders::_1, bind(&foo::b, placeholders::_2));
constexpr auto sumA = bind(plus<int>(), placeholders::_1, bind(&foo::a, placeholders::_2));
constexpr auto sumR = bind(plus<int>(), placeholders::_1, bind(&foo::r, placeholders::_2));
Is there something I could do to make this work?
source to share
There are no technical barriers to building bind
constexpr; for example Sprout C ++ Libraries have constexpr-enabled bind .
However, implementations are not allowed to add constexpr for signatures to work unless they are specified in the standard and there has not yet been a proposal to add constexpr in bind
that I know of ( What parts of the C ++ 14 standard library could be and what parts will constexpr do? ) ... It is rather unlikely that it will be ready, as it bind
is mostly replaced by lambda expressions, which are automatically constexpr as of C ++ 17:
constexpr auto sumB = [](int x, foo const& y) { return x + y.b(); };
source to share
Well, we don't know what it returns std::bind
. Maybe it can be made to work, but there is nothing to make it work (nothing is defined as constexpr
in the spec std::bind
).
In the event that you have access to C ++ 17, you need to use a lambda. In C ++ 17, the operator()
lambda is flagged constexpr
by default, allowing you to do something like
constexpr auto sumB = [](auto val, auto obj) { return val + obj.b(); };
constexpr auto sumA = [](auto val, auto obj) { return val + obj.a(); };
constexpr auto sumR = [](auto val, auto obj) { return val + obj.r(); };
source to share