加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 调用const可变lambdas

发布时间:2020-12-16 07:12:30 所属栏目:百科 来源:网络整理
导读:为简化测试用例,假设我有以下包装类: template typename Tstruct Wrapper { decltype(auto) operator()() const { return m_t(); } decltype(auto) operator()() { return m_t(); } T m_t;};template typename Tauto make_wrapper(T t) { return WrapperT{t
为简化测试用例,假设我有以下包装类:

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闭包.因为我希望它返回非const引用,我设置它是可变的并使用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版本,但是m_t然后被视为const lambda,因此无法调用.我想这是因为m_t首先被标记为可变的.那么这项工作的好方法是什么呢?在调用operator()const之前将m_t转换为非const?

目标

我的目标是调用cwfun()将调用Wrapper :: operator()const和Foo :: operator()const.我可以将Wrapper :: m_t标记为可变以修复编译器错误,但最终会调用Foo :: operator()而不是Foo :: operator()const.

或者,我可以在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,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&>(),class Indexes=std::index_sequence_for<Extra>>
  auto operator()(Extra&&...extra)&&
  -> decltype( apply( std::declval<partial_apply_t&&>(),std::declval<Extra>()... ) )
  {
    return apply( std::move(*this),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.所以lambda根据fun的调用上下文获得了不同的foo结构.

除了上面我可能有一个拼写错误的事实,它应该处理的另一件事是std :: ref之类的,所以当它扩展args时它会将std :: reference_wrap转换为引用.

这应该不难:一个reference_unwrapper传递非引用包装的东西,并解开std :: reference_wrappers.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读