当模板参数是 class 模板时,如何专门化函数模板?

how to do specialize a function template when template parameter is a class template?

例如

template<class T>
T make()
{
   return T();
}

我想在 T 是 class 模板 A 时专门化它;

template<int N>
class A
{};

template<int N>
A<N> make<A<N>>()
{
   ...
};

编译错误:非法使用显式模板参数

怎么做?

您尝试做的是部分专业化,这是不允许的。最好将其包装在 struct.

template<class T>
struct Maker
{
   T make() { return T(); }
};

template<int N>
class A
{};

template<int N>
struct Maker<A<N>>
{
   A<N> make()
   {
      return A<N>();
   }
};

这不是部分特化而是重载。只需删除 <A<N>>:

template<int N>
A<N> make()
{
   ...
};