在类模板外部为指针定义函数

Define a function outside a class template for pointers

本文关键字:指针 定义 函数 外部      更新时间:2023-10-16

我想只为指针模板参数定义一个成员函数,并以另一种方式为其余参数类型定义一个成员函数。我尝试了以下代码:

#include <iostream>
template <class T, class W>
struct A
{
    void foo();
};
template<class T, class W> void A<T*, W*>::foo(){ std::cout << "foo" << std::endl; }
int main(){  }

演示

目前尚不清楚为什么它不起作用。我按照在模板声明中指定的顺序放置指针模板参数。实际上N4296::14.5.1/3 [temp.class]

类模板

名称后面的模板参数列表 成员定义应按照与 一个用于成员的模板参数列表。

那么为什么代码不起作用呢?我按相同的顺序放置参数。

您必须将

整个结构定义为部分专用化,您不能只挑选单个成员进行专用化

[温度.class规格]

1 [...]应在首次使用类模板专用化之前声明部分专业化,该类模板专用化将利用部分专业化作为发生此类使用的每个翻译单元的隐式或显式实例化的结果;无需诊断。

#include <iostream>
template <class T, class W>
struct A
{
  void foo();
};
template<class T, class W>
struct A<T*, W*>
{
  void foo();
};
template<class T, class W> void A<T*, W*>::foo() { std::cout << "foo" << std::endl; }
int main() {}