Capturing this in lambda attribute inside class template without templates

I managed to write a class like this, capturing it in a lambda, defined as a non-static attribute of the specified class:

#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; } 

This compiles and seems to work fine.

However, with the template, it no longer works:

 #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_), decltype(del_)> unique_{&x_, del_}; }; int main() { S<int> s; } 

$> g ++ -std = C ++ 1y custom_deleter_template.cpp
~ / test custom_deleter_template.cpp: when creating 'struct S: custom_deleter_template.cpp: 9: 3: required from' S <> :: S () [c = int] custom_deleter_template.cpp: 24: 10:
required from here custom_deleter_template.cpp: 15: 35: internal compiler error: in tsubst_copy, cp / pt.c: 12569
std :: function del _ {[this] (int * ptr) ^ Please send a full error report with a pre-processed source, if necessary. See for instructions. A pre-processed source stored in the file /tmp/pyro/ccxfNspM.out, please attach this to your report.

Before submitting a bug report (which I can’t make, they blocked the creation of the account), does it not compile normally, based on the standard?

The compiler is g ++ (Ubuntu 4.9.2-0ubuntu1 ~ 14.04) 4.9.2, the -std = C ++ 1y flag is used. The same thing happens with the -std = C ++ 11 flag.

+7
c ++ lambda c ++ 11 templates
source share
1 answer

This is really a bug in GCC that is already being tracked .

This seems to affect 4.8 and 4.9. As noted in the comments, this particular example is great for 4.7 and 5.0. You can see it for yourself here and play with various versions of gcc.

However, this smaller version of your code without an external dependency still crashes from 5.0:

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

I would suggest that you wait until the error I referred to is fixed before using your code, or switch to another compiler;).

0
source share

All Articles