A class with a non-stationary member lambda can't use default template options?

This small test program:

#include <functional> //template<class T> // <-- with this, gcc compiles ok template<class T=void> struct c{ std::function<int(int)> f = [](int i){return i+i;}; }; int main() {}; 

Clang-3.2 compiles this fine, but from GCC 4.7.1 and 4.8 I get a weird error:

 t.cc:6:31: error: default argument for template parameter for class enclosing 'struct __lambda0' function<int(int)> f = [](int i){return i+i;}; ^ 

Is this one of those obscure C ++ rule exceptions that no one knows about, or is this a GCC bug?

EDIT Looks like an error. I logged a bug report

+4
source share
2 answers

I think this is a g ++ error with member initialization by default. I am not sure about this and therefore have the following supporting evidence:

 template<class T=void> struct c { std::function<int(int)> f; c() : f([](int i){return i+i;}) { } }; int main() {} 

If this works, then what you do should work too. And this happens even if you build c .

Personally, I believe that default member initialization should be used sparingly and with care. I think it is very easy to create a lot of confusion with it, because most people expect all initialization to be done in the constructor, and element initializers are not necessarily next to any constructor. In this way, they can leave someone scratching their heads, wondering how a member gets special meaning.

I see cases, especially with simple, mostly data classes, for which it will work very well. But basically, I think that if you have a constructor body of any type, you probably shouldn't use the default member initialization.

+4
source

This code will still get an error with gcc . Yes, without a default argument, it can be compiled. It can be compiled because struct c not used anywhere. But if you try to instantiate this structure, you will receive an error message.

 #include <functional> template<class T> struct c { std::function<int(int)> f = [](int i){return i+i;}; }; int main() { c<int> _c; // error } 

Sounds like a gcc error. This method can help avoid problems.

 #include <functional> #include <iostream> template<class T=void> struct c { c() : f([](int i){return i+i;}) { } std::function<int(int)> f; }; int main() { c<> _c; std::cout << _c.f(10) << std::endl; } 
0
source

Source: https://habr.com/ru/post/1437107/


All Articles