c++ - 为什么 gcc 不能推断数组参数的模板化大小? (C++11)

标签 c++ templates gcc c++11

以下代码给出了一个编译器错误(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 时与 doubleN2 ,它编译得很好(编辑:保留 T 并将 N 替换为 2 个作品,但将 N=2 指定为 N 的默认参数不起作用。)。

  1. 有谁知道为什么 gcc 不能自动绑定(bind)它?
  2. 调用 << 的语法是什么?具有明确指定的模板参数的运算符?

问题 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/

相关文章:

c++ - 是否可以避免 C++ 编译器错误 (C2757),其中 2 个不同的头文件包含相同的命名空间和类符号?

gcc - 如何编译混合的 C 和 C++ 代码?

linux - 堆栈中存储哪些系统数据

c++ - 在新版本的 gcc 上返回隐式不可复制结构的 std::map 时出现编译错误

c++ - 如何将一个 vector 复制到另一个 vector 的末尾?

c++ - unique_ptr 如何同时支持 "dot"和 "arrow"调用以及未定义的方法?

c++ - 使用基于 DirectShow 的虚拟相机和 Electron 框架来渲染 <div> 元素的内容

templates - 部分变量不可见

C++ 将可变参数模板参数扩展为语句

c# - 如何为您的 WPF 应用程序提供平面 (Windows 8) 类型的 UI 外观?