c++ - adding <iostream> breaks the code in g++-7 -


there sample

// example 2: compile?  // // in library header: namespace n { class c {}; } int operator+(int i, n::c) { return i+1; } // mainline exercise it: #include <numeric> int main() {   n::c a[10];   std::accumulate(a, a+10, 0); } 

from "exceptional c++: 47 engineering puzzles, programming problems, , solutions" -- item 34. name lookup , interface principle—part 4

g++ 5.4 compiles successfully. adding #include <iostream> breaks code

// example 2: compile?  // // in library header: namespace n { class c {}; } int operator+(int i, n::c) { return i+1; } // mainline exercise it: #include <numeric> #include <iostream> int main() {     n::c a[10];     std::accumulate(a, a+10, 0); } 

clang-4.0 able compile it. g++ 5.4 , g++7.2.0 show following error

in file included /usr/include/c++/7/numeric:62:0,                  src/widget.cpp:7: /usr/include/c++/7/bits/stl_numeric.h: in instantiation of ‘_tp std::accumulate(_inputiterator, _inputiterator, _tp) [with _inputiterator = n::c*; _tp = int]’: src/widget.cpp:12:35:   required here /usr/include/c++/7/bits/stl_numeric.h:127:18: error: no match ‘operator+’ (operand types ‘int’ , ‘n::c’)   __init = __init + *__first;            ~~~~~~~^~~~~~~~~~ 

looks bug in g++. i'm interested know if workaround exists?

if curios me - i'm posting have understood further reading in book.

compiler operator+ called std::accumulate starting namespace std.

only if no candidates found in namespace - go , global namespace candidates.

so original sample , modified sample in clang compiled pure luck no operator+ declared before std::accumulate.

as new header added game - compiler stopped global namespace , stopped seeing proper operator candidate @ all.

best match not , cause strange error messages.

now moving operator+ namespace n initiating koenig lookup - if 1 of function arguments in namespace n - suitable candidates should looked in namespace addition regular lookup.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -