Most vexing parse
“Everything that resembles a function is a function.”
C++03
struct Bar { }; struct Foo { Foo() : x(0) {} Foo(const Bar&) : x(1) {} Foo(const Bar&, const Bar&) : x(2) {} int x; }; int main() { Foo a(); Foo b(Bar()); Foo c(Bar(), Bar()); std::cout << a.x << std::endl; std::cout << b.x << std::endl; std::cout << c.x << std::endl; }
Result
Line 17: request for member ‘x’ in ‘a’, which is of non-class type ‘Foo()’
Line 18: request for member ‘x’ in ‘b’, which is of non-class type ‘Foo(Bar (*)())’
Line 19: request for member ‘x’ in ‘c’, which is of non-class type ‘Foo(Bar (*)(), Bar (*)())’
C++11
int main() { Foo a{}; // or just: Foo a; Foo b{Bar()}; Foo c{Bar(), Bar()}; std::cout << a.x << std::endl; std::cout << b.x << std::endl; std::cout << c.x << std::endl; }
Result
0
1
2
Container initialization
“It’s not easy to initialize a container, bar some fancy comma operator tricks.”
C++03
struct Foo { Foo() : _container() { _container.push_back(1); _container.push_back(2); _container.push_back(3); _container.push_back(4); _container.push_back(5); _container.push_back(6); _container.push_back(7); } // Alternative Foo(int) : _container(helper()) { } static std::vector<int> helper() { std::vector<int> result; result.push_back(1); result.push_back(2); result.push_back(3); result.push_back(4); result.push_back(5); result.push_back(6); result.push_back(7); return result; } std::vector<int> _container; };
C++11
struct Foo { Foo() : _container{ 1, 2, 3, 4, 5, 6, 7 } { } std::vector<int> _container; };
Brief constructors
You (almost) always have to specify the constructor name.
C++03
struct YouDontWantToSpellThis { YouDontWantToSpellThis(int a, int b) { ; } }; std::vector<YouDontWantToSpellThis> container; container.push_back(YouDontWantToSpellThis(1, 2));
C++11
container.push_back({1, 2});
Tags: C++11x, initializer list
Leave a comment