没有前向声明的嵌套函数模板实例在GCC上编译,但不在clang上编译
以下内容不能在 clang 中编译,但可以在 GCC ( Godbolt )中编译:
template <typename K, typename V>
std::ostream& operator<< (std::ostream& o, const std::map<K, V>& map)
{
const char* sep = "{";
for (const auto& x : map)
{
o << sep << "{" << x.first << ", " << x.second << "}";
sep = ", ";
}
return o << "}";
}
template <typename T>
std::ostream& operator<< (std::ostream& o, const std::vector<T>& vec)
{
const char* sep = "{";
for (const auto& x : vec)
{
o << sep << x;
sep = ", ";
}
return o << "}";
}
// Usage
int main()
{
std::map<int, std::vector<int>> t = {{1, {2, 3}}, {4, {5}}};
std::cout << t << std::endl;
return 0;
}
谁是对的?
顺便说一句,我知道它是 UB,但是将两个模板定义放入其中也namespace std会使代码在 clang 上编译。
借用的代码是否可以为模板类型定义 operator<<?