有样品
// 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);
}
Run Code Online (Sandbox Code Playgroud)
摘自"Exceptional C++:47工程难题,编程问题和解决方案" - 第34项.名称查找和接口原理 - 第4部分
g ++ 5.4成功编译它.但添加#include <iostream>破坏了代码
// Example 2: Will this compile?
//
// In some library header:
namespace N { class C {}; }
int operator+(int i, N::C) …Run Code Online (Sandbox Code Playgroud) // main.cpp
Run Code Online (Sandbox Code Playgroud)
#include <iostream>
#include <utility>
#include <algorithm>
#include <iterator>
#include <map>
template<typename t1, typename t2>
std::ostream& operator<<(std::ostream& os, const std::pair<t1, t2>& pair)
{
return os << "< " << pair.first << " , " << pair.second << " >";
}
int main()
{
std::map<int, int> map = { { 1, 2 }, { 2, 3 } };
std::cout << *map.begin() << std::endl;//This works
std::copy(
map.begin(),
map.end(),
std::ostream_iterator<std::pair<int,int> >(std::cout, " ")
); //this doesn't work
}
Run Code Online (Sandbox Code Playgroud)
no match for ‘operator<<’ …