c++ - 为什么我不能构造一个绑定(bind)?

标签 c++ c++11 bind functor constexpr

假设我想创建一些 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? )。这是不太可能的,因为 bindmostly 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/

相关文章:

c++将函数放在单独的源文件中

c++ - std::list.size() 如何具有恒定的复杂性?

c++ - C++中 `inserter`的机制是什么?

c++ - 在哪里可以找到最新的 C++14 标准草案

c++ - std::bind 返回的类型可以默认构造吗?

c++ - 成员函数指针错误,boost bind

c++ - 不使用 cv::imdecode() 从多个 JPEG 编码图像创建 MJEPG 视频

c++ - 排序后在未排序数组中查找元素位置的最佳方法

c++ - 我如何将 "map"参数包

python - Tkinter 文本标记范围从开始和结束索引值从 wordstart 到 wordend?