为什么 gcc 无法推断数组参数的模板化大小?(C++11)
Why can't gcc deduce templated size for array argument? (C++11)
以下代码给出了一个编译器错误(gcc-4.7 使用 -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}' lvalue to
"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<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits; _Tp = std::array]'
当我摆脱模板函数声明并将T
替换为 double
并用 2
替换N
时,它的编译效果很好(编辑:保留 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;
}
非常感谢您的帮助。
考虑你的声明:
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
,这就是它不匹配的原因。
您可以使用指定的模板参数以这种不太美观的方式调用operator<<
:
operator<< <double,2>(std::cout, lower) << std::endl;
- GCC:使用 c++11 时发出警告
- C++11/14/17,GCC 7 与 GCC 8:好友类模板的名称查找
- 为什么 GCC 6.3 在没有显式 C++11 支持的情况下编译此大括号初始化列表代码
- C 11螺纹 - 非静态成员功能的使用无效 - 工作GCC 5.1.0损坏的GCC 7.3.1
- 这被认为是有效的C 11还是C 14?还是GCC/Clang弄错了
- GCC:当层次结构中存在虚拟继承时,C++11 内联对象初始化(使用 "this")不起作用
- C 11 std :: This_thread :: Sleep_until()用GCC 4.8.5编译时挂起
- ANTLR4-帮助与GCC(GCC)4.4.7 20120313(红帽4.4.7-11)一起使用
- Docker GCC中的C 11:5图像
- 使用GCC v4.8在Ubuntu 14.04上定义C 11中元组向量时的编译错误
- 即使明确指定了98个标准,GCC也使用C 11标准
- 在Linux中使用gcc 4.1编译的C++03应用程序中使用C++11共享库
- C++11 具有与不同版本的 GCC 兼容的功能
- GCC:Get LD:对于架构X86_64在OS X 10.11.5上找不到的符号
- C 11在Mac上具有clang或GCC
- 使用 GCC 和 C++11 实施类型 "long double"
- GCC C++11 对用户定义的常量和模板参数包的限制
- C++11:GCC 4.8 静态thread_local std::unique_ptr 未定义的引用
- C++11 GCC 4.6.2标准::移动
- C++11 gcc:声明中的显式限定?标准参考号