以下代码给出了一个编译器错误(gcc-4.7 run with -std=c++11
):
#include <iostream>
#include <array>
template <typename T, int N>
std::ostream & operator <<(std::ostream & os, const std::array<T, N> & arr) {
int i;
for (i=0; i<N-1; ++i)
os << arr[i] << " ";
os << arr[i];
return os;
}
int main() {
std::array<double, 2> lower{1.0, 1.0};
std::cout << lower << std::endl;
return 0;
}
错误信息:
tmp6.cpp: In function ‘int main()’: tmp6.cpp:16:16: error: cannot bind
‘std::ostream {aka std::basic_ostream}’ lvalue to
‘std::basic_ostream&&’ In file included from
/usr/include/c++/4.7/iostream:40:0,
from tmp6.cpp:1: /usr/include/c++/4.7/ostream:600:5: error: initializing argument 1 of ‘std::basic_ostream<_CharT,
_Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits; _Tp = std::array]’
当我摆脱模板函数声明并替换 T
时与 double
和 N
与 2
,它编译得很好(编辑:保留 T
并将 N
替换为 2 个作品,但将 N=2
指定为 N
的默认参数不起作用。)。
- 有谁知道为什么 gcc 不能自动绑定(bind)它?
调用<<
的语法是什么?具有明确指定的模板参数的运算符?
问题 2 的答案: operator<<<double, 2>(std::cout, lower);
编辑:以下函数也是如此,它仅在数组大小中进行模板化:
template <int N>
void print(const std::array<double, N> & arr) {
std::cout << "print array here" << std::endl;
}
int main() {
std::array<double, 2> lower{1.0, 1.0};
print<2>(lower); // this works
print(lower); // this does NOT work
return 0;
}
非常感谢您的帮助。
最佳答案
考虑你的声明:
template <typename T, int N>
std::ostream & operator <<(std::ostream & os, const std::array<T, N> & arr) {
std::array
的定义是:
template<typename T, std::size_t N> class array {...};
您正在使用 int
而不是 std::size_t
,这就是它不匹配的原因。
关于c++ - 为什么 gcc 不能推断数组参数的模板化大小? (C++11),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10866489/