简体   繁体   中英

Template specialization only in class scope

I have a class templatized on a parameter N, in it's own header file reproduction.H:

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

I'm trying to provide different specializations for the function depending on N.

In the.C file, I have:

#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>;

And gcc 6 with c++14 gives me error

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();

But, if I drop the N, and just have

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

That compiles, and

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

compiles.

Why would the first case fail, but the next two pass?

This

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

is definition of a member function of a primary template.

This

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

is explicit specialization of the same member function.

This

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

is invalid because the template argument list does not correspond to the template parameter list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM