草庐IT

c++ - 调用 const 可变 lambda

coder 2024-02-25 原文

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

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++ - 调用 const 可变 lambda的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  3. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  4. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  5. ruby - 调用其他方法的 TDD 方法的正确方法 - 2

    我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent

  6. 【鸿蒙应用开发系列】- 获取系统设备信息以及版本API兼容调用方式 - 2

    在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList​()Obt

  7. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  8. C51单片机——实现用独立按键控制LED亮灭(调用函数篇) - 2

    说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时

  9. ruby - 如何找到调用当前方法的方法 - 2

    如何找到调用此方法的位置?defto_xml(options={})binding.pryoptions=options.to_hifoptions&&options.respond_to?(:to_h)serializable_hash(options).to_xml(options)end 最佳答案 键入caller。这将返回当前调用堆栈。文档:Kernel#caller.例子[0]%rspecspec10/16|===================================================62=====

  10. ruby-on-rails - 使用 HTTParty 的非常基本的 Rails 4.1 API 调用 - 2

    Rails相对较新。我正在尝试调用一个API,它应该向我返回一个唯一的URL。我的应用程序中捆绑了HTTParty。我已经创建了一个UniqueNumberController,并且我已经阅读了几个HTTParty指南,直到我想要什么,但也许我只是有点迷路,真的不知道该怎么做。基本上,我需要做的就是调用API,获取它返回的URL,然后将该URL插入到用户的数据库中。谁能给我指出正确的方向或与我分享一些代码? 最佳答案 假设API为JSON格式并返回如下数据:{"url":"http://example.com/unique-url"

随机推荐