为什么我无法获得绑定?
所以说,我想做一些constexpr
函数,我虽然可以使用bind
做到这一点。有什么我失踪? bind
为什么不能返回constexpr
?为什么我无法获得绑定?
考虑:
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;
};
我想:
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));
有什么我可以做,以使这项工作?
不存在技术障碍,使bind
constexpr;例如,Sprout C++ Libraries有constexpr-enabled bind。
但是,implementations are not permitted to add constexpr to function signatures where it is not specified in the Standard,并且还没有任何提议将constexpr添加到我知道的bind
(Which parts of the C++14 Standard Library could be and which parts will be made constexpr?)。这是相当不可能的,一个是即将到来的,因为bind
是mostly superseded通过lambda表达式,其形式为C++ 17自动constexpr:
constexpr auto sumB = [](int x, foo const& y) { return x + y.b(); };
这太好了,因为它回答了我为什么当它们无法像lambda表达式捕获时那样'bind' results'constexpr'的深层问题,因此在编译时应该是完全可定义的。 –
那么,我们不知道什么std::bind
返回。它可能会工作,但没有任何要求使其工作(没有任何东西在std::bind
的规范中定义为constexpr
)。
在你可以做的事情上,如果你有权访问C++ 17,那就是使用lambda。在C++ 17的拉姆达的operator()
将被标记为默认constexpr
允许你这样做
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(); };
'std :: bind'无法返回'std :: function'。 – Yakk
@Yakk好吧,TIL。感谢您的信息。答案已被编辑。 – NathanOliver
如果你想知道为什么,'std :: bind'的返回值必须有一个模板化的'operator()',*和*它传递给另一个绑定表达式时必须有某些属性; 'std :: function'没有这些属性。 – Yakk
的问题可能是现在“为什么不能”,而是“为什么没有按“T”。它可能会,但事实并非如此。 –
@NathanOliver我认为这将是一个很好的答案。你介意张贴吗? –