首页 > 解决方案 > 如何将这个模板化的类函数声明为朋友?

问题描述

模板让事情变得如此困难。我没有正确的语法,我已经尝试了很多年。我在一个名为“ModelMngr”的类中有一个名为“createSphere”的函数,我想成为另一个类的朋友。

class ModelMngr
{public:
template <typename T_scalar>
    static Sphere<T_scalar>* createSphere(T_scalar radius, int sides, int heightSegments, const String& name = "Sphere Primitive Mesh");
}

template <typename T_scalar>
class Sphere : public MeshBaseClass<T_scalar>
{public:
        template <typename T> friend Sphere<T>* ModelMngr::createSphere(T radius, int sides, int heightSegments, const String& name = "Sphere Primitive Mesh");


}

我将朋友声明中的 T_scalar 更改为 T,因为我担心会与封闭类的模板参数发生名称冲突。有没有冲突?

标签: c++templatesfriend

解决方案


转发声明Sphere,从朋友声明中删除默认参数并在类定义后添加分号:

template <typename T_scalar>
class Sphere;

class ModelMngr {
public:
  template <typename T_scalar>
  static Sphere<T_scalar> *
  createSphere(T_scalar radius, int sides, int heightSegments,
               const String& name = "Sphere Primitive Mesh");
};

template <typename T_scalar>
class Sphere : public MeshBaseClass<T_scalar> {
public:
  template <typename T>
  friend Sphere<T> *
  ModelMngr::createSphere(T radius, int sides, int heightSegments,
                          const String &name);
};

推荐阅读