【问题标题】:How do I declare this templated class function as a friend?如何将此模板化类函数声明为朋友?
【发布时间】:2020-12-24 05:16:46
【问题描述】:

模板让事情变得如此困难。我没有正确的语法,我已经尝试了很多年。我在一个名为“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++ 模板:完整指南 [David Vandevoorde 和 Nicolai M. Josuttis]

标签: c++ templates friend


【解决方案1】:

转发声明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);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 2019-01-29
    相关资源
    最近更新 更多