【问题标题】:Why Can't I constexpr a bind?为什么我不能 constexpr 绑定?
【发布时间】:2017-07-28 14:21:58
【问题描述】:

假设我想制作一些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));

我可以做些什么来完成这项工作吗?

【问题讨论】:

  • 现在的问题可能是“为什么不能”但“为什么不能”。它可能可以,但它没有。
  • @NathanOliver 我认为这将是一个很好的答案。你介意发帖吗?

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


【解决方案1】:

制作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,据我所知 (Which parts of the C++14 Standard Library could be and which parts will be made constexpr?),目前还没有任何将 constexpr 添加到 bind 的建议。不太可能出现,因为 bind 是 lambda 表达式的 mostly superseded,从 C++17 开始,它自动成为 constexpr:

constexpr auto sumB = [](int x, foo const& y) { return x + y.b(); };

【讨论】:

  • 这很好,因为它回答了我更深层次的问题,即为什么 bind 不能在不能像 lambdas 这样捕获时得到 constexpr,因此应该在编译时完全定义。
【解决方案2】:

好吧,我们不知道std::bind 会返回什么。它可能可以工作,但没有任何强制要求使其工作(在std::bind 的规范中没有定义为constexpr)。

但是,如果您可以访问 C++17,您可以做的就是使用 lambda。在 C++17 中,lambda 的 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(); };

Live Example

【讨论】:

  • std::bind 不能返回 std::function
  • @Yakk 好吧,TIL。感谢您的信息。答案已被编辑。
  • 如果您想知道原因,std::bind 的返回值必须有一个模板化的operator()并且它在传递给另一个绑定表达式时必须具有某些属性; std::function 没有这些属性。
猜你喜欢
  • 2014-02-27
  • 2013-09-09
  • 1970-01-01
  • 1970-01-01
  • 2018-02-25
  • 2012-01-17
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多