假设我想创建一些 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(); };
关于c++ - 为什么我不能构造一个绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45375878/