如何将模板友元函数声明到模板类

How can I declare a template friend function to a template class?

本文关键字:声明 函数 友元      更新时间:2023-10-16

抱歉,这个问题似乎被问了很多次,但我无法获得适用于我的设置的其他答案。我有以下类和函数设置:

namespace ddd {
  template <typename T>
  class A {
    ...
  };
  template <typename T, typename U>
  A<T> a_func(const A<U> &a) {
    ...
  }
}

我想将a_func声明为 A 的好友,并且我希望它使 a_func 是 A 的所有实例的好友,无论 T 和 U 使用哪种类型名(例如,a_func可以访问 A(。

谢谢!

你可以这样做(看起来像你拥有它的方式(:

template<typename X>
class A {
    template<typename T, typename U>
    friend A<T> a_func(const A<U>& a);
};
template<typename T, typename U>
A<T> a_func(const A<U>& a) {
    // whatever
}

演示