c – 在模板化类和非模板化类中的lambda属性中捕获它

c – 在模板化类和非模板化类中的lambda属性中捕获它,第1张

概述我已经成功编写了一个像这样的类,在一个被定义为所述类的非静态属性的lambda中捕获它: #include <memory>#include <iostream>#include <functional>struct S{ S() { std::cout << "S::S()[" << this << "]" << std::endl; } std::strin 我已经成功编写了一个像这样的类,在一个被定义为所述类的非静态属性的lambda中捕获它:
#include <memory>#include <iostream>#include <functional>struct S{  S()  {    std::cout << "S::S()[" << this << "]" << std::endl;  }  std::string y_{"hi mate"};  int x_;  std::function<voID(int*)> del_{[this](int *ptr)  {    std::cout << "Deleting ptr[" << ptr << "] this[" << this << "] this->y_[" << this->y_ << "]" << std::endl;  }};  std::unique_ptr<decltype(x_),decltype(del_)> unique_{&x_,del_};};int main(){  S s;}

这编译并且似乎运行得很好.

但是,对于模板化的类,它不再起作用:

#include <memory>#include <iostream>#include <functional>template <typename>struct S{  S()  {    std::cout << "S::S()[" << this << "]" << std::endl;  }  std::string y_{"hi mate"};  int x_;  std::function<voID(int*)> del_{[this](int *ptr)  {    std::cout << "Deleting ptr[" << ptr << "] this[" << this << "] this->y_[" << this->y_ << "]" << std::endl;  }};  std::unique_ptr<decltype(x_),del_};};int main(){  S<int> s;}

$> g++ -std=c++1y custom_deleter_template.cpp
~/test custom_deleter_template.cpp: In instantiation of ‘struct
S::’: custom_deleter_template.cpp:9:3: required
from ‘S< >::S() [with
= int]’ custom_deleter_template.cpp:24:10:
required from here custom_deleter_template.cpp:15:35: internal
compiler error: in tsubst_copy,at cp/pt.c:12569
std::function del_{[this](int *ptr)
^ Please submit a full BUG report,with preprocessed source if appropriate. See
for instructions.
Preprocessed source stored into /tmp/pyro/ccxfNspM.out file,please
attach this to your BUGreport.

在提交BUG报告之前(我不能做,他们阻止了帐户创建),根据标准所说的,它不能编译是正常的吗?

编译器是g(Ubuntu 4.9.2-0ubuntu1~14.04)4.9.2,使用标志-std = c 1y.标志-std = c 11也会发生同样的事情.

解决方法 这确实是GCC中的一个错误,已经是 being tracked了.

它似乎影响4.8和4.9.正如评论中指出的那样,这个特殊的例子适用于4.7和5.0.你可以看到自己here并玩不同版本的gcc.

但是,这个没有外部依赖的代码缩减版仍然会崩溃5.0:

template <typename>struct S {  int f{[this](){return 42;}()};};int main(){    return S<int>{}.f; //  should return 42}

我建议您在使用代码之前等待我引用的错误,或者切换到另一个编译器;).

总结

以上是内存溢出为你收集整理的c – 在模板化类和非模板化类中的lambda属性中捕获它全部内容,希望文章能够帮你解决c – 在模板化类和非模板化类中的lambda属性中捕获它所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1239643.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存