【发布时间】:2012-06-07 15:38:22
【问题描述】:
以下代码给出编译器错误(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:在函数“int main()”中:tmp6.cpp:16:16:错误:无法绑定
'std::ostream {aka std::basic_ostream}' 左值
'std::basic_ostream&&' 在包含的文件中
/usr/include/c++/4.7/iostream:40:0,
来自 tmp6.cpp:1: /usr/include/c++/4.7/ostream:600:5: 错误: 初始化‘std::basic_ostream<_chart>的参数1 _Traits>& std::operator&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits; _Tp = std::array]'
当我摆脱模板函数声明并将T替换为double并将N替换为2时,它编译得很好(编辑:离开T并将N替换为2 有效,但将 N=2 指定为 N 的默认参数不起作用。)。
- 有人知道为什么 gcc 不能自动绑定这个吗?
使用显式指定的模板参数调用<<运算符的语法是什么?
问题 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;
}
非常感谢您的帮助。
【问题讨论】:
-
请注意,您不应该为标准类型定义
operator <<。 -
@K-ballo 知道如何回答帖子中的两个编号问题吗?
-
如果我能回答,我会给出答案而不是评论......问题可能来自以错误的方式实现运算符。
-
@K-ballo 可以使用函数
template <int N> print (const std::array<double, N> & arr) { /*...*/ }提出相同的问题。我想知道为什么 gcc 不能绑定这个... -
你的意思是
print( lower );不会编译?您能否将print版本的测试用例添加到您的问题中?