仅在 class 范围内的模板专业化

Template specialization only in class scope

我在参数 N 上有一个 class 模板化,在它自己的头文件中 reproduction.H:

#include <cstdlib>
#include <array>
template<std::size_t N>
class A{
  private:
  std::array<float, N> foo();
};

我正在尝试根据 N 为函数提供不同的专业化。

在.C文件中,我有:

#include "reproduction.H"
#include <tuple>

template <std::size_t N>
std::array<float,N> A<2>::foo(){return std::array<float, N>();}

template class A<2>;

使用 c++14 的 gcc 6 给我错误

reproduction.C:5:21: error: prototype for 'std::array<float, N> A<2ul>::foo()' does not match any in class 'A<2ul>'
 std::array<float,N> A<2>::foo(){return std::array<float, N>();}
                     ^~~~
In file included from reproduction.C:1:0:
reproduction.H:6:24: error: candidate is: std::array<float, N> A<N>::foo() [with long unsigned int N = 2ul]
   std::array<float, N> foo();

但是,如果我去掉 N,就只有

template <>
std::array<float,2> A<2>::foo(){return std::array<float, 2>();}

编译,

template <std::size_t N>
std::array<float,N> A<N>::foo(){return std::array<float, N>();}

编译。

为什么第一个案例会失败,但接下来的两个案例会通过?

这个

template <std::size_t N>
std::array<float,N> A<N>::foo(){return std::array<float, N>();}

是主模板的成员函数定义。

这个

template <>
std::array<float,2> A<2>::foo(){return std::array<float, 2>();}

是同一成员函数的显式特化。

这个

template <std::size_t N>
std::array<float,N> A<2>::foo(){return std::array<float, N>();}

无效,因为模板参数列表与模板参数列表不对应。