Adding <iostream> breaks code in g ++ - 7

There is a sample

// Example 2: Will this compile? 
//
// In some library header:
namespace N { class C {}; }
int operator+(int i, N::C) { return i+1; }
// A mainline to exercise it:
#include <numeric>
int main()
{
  N::C a[10];
  std::accumulate(a, a+10, 0);
}

From "Exceptional C ++: 47 Puzzles, Programming Problems, and Solutions" - clause 34. Search for a name and interface principle - part 4

g ++ 5.4 will compile it successfully. But adding #include <iostream>breaks the code

// Example 2: Will this compile? 
//
// In some library header:
namespace N { class C {}; }
int operator+(int i, N::C) { return i+1; }
// A mainline to exercise it:
#include <numeric>
#include <iostream>
int main()
{
    N::C a[10];
    std::accumulate(a, a+10, 0);
}

clang-4.0 is able to compile it. g ++ 5.4 and g ++ 7.2.0 show the following error:

In file included from /usr/include/c++/7/numeric:62:0,
                 from 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 from here
/usr/include/c++/7/bits/stl_numeric.h:127:18: error: no match for β€˜operator+’ (operand types are β€˜int’ and β€˜N::C’)
  __init = __init + *__first;
           ~~~~~~~^~~~~~~~~~

Looks like a bug in g ++. I am interested to know if there is a workaround?

+6
source share
1 answer

IF someone is as curious as I am - I am publishing what I understood from further reading in the book.

The compiler will look for the + operator called from std :: accumulate, starting with the std namespace.

, , .

, clang , operator + , std:: accumulate.

- , .

.

+ N Koenig - N - , .

+6

All Articles