c++ - 调用 const 可变 lambda

标签 c++ c++11 c++14

为了简化测试用例,假设我有以下包装类:

template <typename T>
struct Wrapper {
  decltype(auto) operator()() const {
    return m_t();
  }
  decltype(auto) operator()() {
    return m_t();
  }
  T m_t;
};

template <typename T>
auto make_wrapper(T t) {
  return Wrapper<T>{t};
}

假设我包装了以下简单的仿函数返回引用:

struct Foo {
  int& operator()() {
    return x;
  }
  const int& operator()() const {
    return x;
  }
  int x;
};

在我的 main 函数中,我试图将 Foo 仿函数包装到一个 lambda 闭包中。因为我希望它返回非常量引用,所以我将它设置为 mutable 并使用 decltype(auto):

int main() {
  Foo foo;
  auto fun = [foo]() mutable -> decltype(auto) { return foo(); };
  auto wfun = make_wrapper(fun);
  const auto& cwfun = wfun;

  wfun();     // <- OK
  cwfun();    // <- BAD!
}

对于第二次调用,cwfun(),调用了 Wrapper::operator() 的第一个 const 版本,但是 code>m_t 然后被视为 const lambda,因此无法调用。我想这是因为 m_t 首先被标记为 mutable。那么,什么是完成这项工作的好方法呢?在 operator() const 中调用之前将 m_t 转换为非 const

目标

我的目标是调用 cwfun() 将调用 Wrapper::operator() constFoo::operator() const。我可以将 Wrapper::m_t 标记为 mutable 来修复编译器错误,但是最终将调用 Foo::operator() 而不是Foo::operator() 常量

或者,我可以在 Wrapper::operator() const 中添加一个 const,因为我知道 Foo::operator() 并且Foo::operator() const 只是它们的常量不同。使用类似的东西:

return const_cast<typename std::add_lvalue_reference<typename std::add_const<typename std::remove_reference<decltype(m_t())>::type>::type>::type>(m_t());

但是,是的,那很重。

错误和 Coliru 粘贴

clang 给出的错误信息如下:

tc-refptr.cc:8:12: error: no matching function for call to object of type 'const (lambda at
      tc-refptr.cc:40:14)'
    return m_t();
           ^~~
tc-refptr.cc:44:27: note: in instantiation of member function 'Wrapper<(lambda at
      tc-refptr.cc:40:14)>::operator()' requested here
  DebugType<decltype(cwfun())> df;
                          ^
tc-refptr.cc:40:14: note: candidate function not viable: 'this' argument has type 'const
      (lambda at tc-refptr.cc:40:14)', but method is not marked const
  auto fun = [foo]() mutable -> decltype(auto) { return foo(); };

Code on Coliru

最佳答案

首先我们从 partial_apply 开始,在本例中它被写成对 const 敏感:

template<class F, class...Args>
struct partial_apply_t {
  std::tuple<Args...> args;
  F f;
  template<size_t...Is, class Self, class...Extra>
  static auto apply( Self&& self, std::index_sequence<Is...>, Extra&&...extra )
  -> decltype(
    (std::forward<Self>(self).f)(
      std::get<Is>(std::forward<Self>(self).args)...,
      std::declval<Extra>()...
    )
  {
    return std::forward<Self>(self).f(
      std::get<Is>(std::forward<Self>(self).args)...,
      std::forward<Extra>(extra)...
    );
  }
  partial_apply_t(partial_apply_t const&)=default;
  partial_apply_t(partial_apply_t&&)=default;
  partial_apply_t& operator=(partial_apply_t const&)=default;
  partial_apply_t& operator=(partial_apply_t&&)=default;
  ~partial_apply_t()=default;
  template<class F0, class...Us,
    class=std::enable_if_t<
      std::is_convertible<std::tuple<F0, Us...>, std::tuple<F, Args...>>{}
    >
  >
  partial_apply_t(F0&& f0, Us&&...us):
    f(std::forward<F0>(f0)),
    args(std::forward<Us>(us)...)
  {}
  // three operator() overloads.  Could do more, but lazy:
  template<class...Extra, class Indexes=std::index_sequence_for<Extra>>
  auto operator()(Extra&&...extra)const&
  -> decltype( apply( std::declval<partial_apply_t const&>(), Indexes{}, std::declval<Extra>()... ) )
  {
    return apply( *this, Indexes{}, std::forward<Extra>(extra)... );
  }
  template<class...Extra, class Indexes=std::index_sequence_for<Extra>>
  auto operator()(Extra&&...extra)&
  -> decltype( apply( std::declval<partial_apply_t&>(), Indexes{}, std::declval<Extra>()... ) )
  {
    return apply( *this, Indexes{}, std::forward<Extra>(extra)... );
  }
  template<class...Extra, class Indexes=std::index_sequence_for<Extra>>
  auto operator()(Extra&&...extra)&&
  -> decltype( apply( std::declval<partial_apply_t&&>(), Indexes{}, std::declval<Extra>()... ) )
  {
    return apply( std::move(*this), Indexes{}, std::forward<Extra>(extra)... );
  }
};
template<class F, class... Ts>
partial_apply_t<std::decay_t<F>, std::decay_t<Ts>...>
partial_apply(F&& f, Ts&&...ts) {
  return {std::forward<F>(f), std::forward<Ts>(ts)...};
}

然后我们使用它:

auto fun = partial_apply(
  [](auto&& foo) -> decltype(auto) { return foo(); },
  foo
);

现在 foo 的拷贝存储在 partial_apply 中,并且在我们调用它的时候它被传递(以正确的 const-correctness)到 lambda .因此,根据 fun 的调用上下文,lambda 会获得不同的 foo const-ness。

除了上面我可能有错字之外,它应该处理的另一件事是 std::ref 等,这样当它扩展 args 时将 std::reference_wrapper 转换为引用。

这应该不难:reference_unwrapper 传递非引用包装的东西,并解包 std::reference_wrapper

或者,我们可以在 partial_apply 函数中解包,而不是 decay_ting。

关于c++ - 调用 const 可变 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30605466/

相关文章:

C++ - 具有相同设置的新 SFML 项目

c++ - 如何创建指向无法修改指向地址的数组的指针?

c++ - 为什么在c++14中定义了shared_timed_mutex,而在c++17中定义了shared_mutex?

c++ - 自 C++14 以来,总是更喜欢 set<T, less<>> 到 set<T>?

c++ - 命名空间正确性

c++ - 双重乘法的模板元编程

c++ - 将int的所有字节都设置为(unsigned char)0,保证代表零?

c++ - 可变参数模板中的分支

c++ - libc++ 的 std::basic_string 的 16 字节对齐模式背后的原因是什么?

c++ - 'std::thread' 的初始化没有匹配的构造函数