为什么gcc不能推导出数组参数的模板大小?(C++ 11)

use*_*ser 10 c++ gcc templates 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;
}
Run Code Online (Sandbox Code Playgroud)

错误信息:

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 <<(std :: basic_ostream <_CharT,_Traits> &&,const _Tp&)[with _CharT = char; _Traits = std :: char_traits; _Tp = std :: array]'

当我摆脱模板函数声明并替换TdoubleNwith时2,它编译得很好(编辑:离开T并替换N为2个作品,但指定N=2为默认参数N不起作用.).

  1. 有谁知道为什么gcc不能自动绑定这个?
  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;
}
Run Code Online (Sandbox Code Playgroud)

非常感谢你的帮助.

K-b*_*llo 13

考虑你的声明:

template <typename T, int N>
std::ostream & operator <<(std::ostream & os, const std::array<T, N> & arr) {
Run Code Online (Sandbox Code Playgroud)

定义std::array是:

template<typename T, std::size_t N> class array {...};
Run Code Online (Sandbox Code Playgroud)

你正在使用int而不是std::size_t,这就是为什么它不匹配.