函数模板的显式专门化,用于完全专门化的类模板

Explicit specialization of a function template for a fully specialized class template

本文关键字:专门化 函数模板 用于      更新时间:2023-10-16

我试图在类模板的专门化中专门化一个函数,但无法找到正确的语法:

template< typename T >
struct Foo {};
template<>
struct Foo< int >
{
  template< typename T >
  void fn();
};
template<> template<>
void Foo< int >::fn< char >() {} // error: too many template-parameter-lists

在这里,我试图将fn专门化为char,这是在专门化intFoo内部。但是编译器不喜欢我写的东西。那么什么应该是正确的语法呢?

你不必说你专业化了两次。

您只在此处专门化一个功能模板

template<> void Foo<int>::fn<char>() {}

在Coliru上直播

template< typename T >
struct Foo {};
template<>
struct Foo< int >
{
  template< typename T >
  void fn();
};
template<> void Foo<int>::fn<char>() {}
int main() {
    Foo<int> f;
    f.fn<char>();
}