如何为流输出运算符提供重载<<模板'using'类型别名?

How to provide an overload for the stream output operator << for a template 'using' type alias?

本文关键字:lt 模板 using 别名 类型 重载 输出 运算符      更新时间:2023-10-16

>有人知道为什么这不能编译以及如何修复它吗?不知何故,编译器找不到流运算符的正确模板实例化,但我不明白为什么。

#include <array>
#include <iostream>
template <int N>
using Row = std::array<int, N>;
template <int N>
std::ostream& operator <<(std::ostream& o, const Row<N>& mc) {
for (auto i : mc)
o << i << " ";
return o;
}
int main(int argc, char *argv[]) {
Row<4> row {};
std::cout << row << std::endl;
}

有谁知道为什么这不编译以及如何修复它?

是的:问题是您声明Row正在接收int

template <int N>
using Row = std::array<int, N>;

并尝试在运算符中拦截它的大小作为int,当std::array收到(对于第二个参数(一个std::size_t

因此,您的Row<4>(即std::array<int, 4u>4ustd::size_t(与您的运算符不匹配,因为运算符会查找Nintstd::array<int, N>

修复:将Row定义为接收std::size_t(可选,只是为了清楚起见(,并在运算符中推断出std::size_t(强制(。

template <std::size_t N> // <--- you have to intercept a std::size_t
std::ostream& operator <<(std::ostream& o, const Row<N>& mc) {
for (auto i : mc)
o << i << " ";
return o;
}

替代 C++17 修复:截获运算符大小作为auto

template <auto N> // <--- auto can intercept a std::size_t
std::ostream& operator <<(std::ostream& o, const Row<N>& mc) {
for (auto i : mc)
o << i << " ";
return o;
}