如何摆脱重复写入 namespace_name:: inside class headers

How to get rid of repeatedly writing namespace_name:: inside class headers

我有一个 class,它广泛使用特定命名空间的成员,如下所示:

class Entity {

    using namespace glm;

  public:

    Entity(vec3 position, vec3 direction, vec3 upVector, vec3 velocity, float speed = 0.0f);
    Entity(vec3 position, vec3 direction, vec3 upVector);
    Entity(vec3 position, vec3 direction);
    virtual ~Entity() {}

    vec3 position()   { return this->pos; }
    vec3 direction()  { return this->dir; }
    vec3 upVector()   { return this->upVec; }
    vec3 velocity()   { return this->vel; }
    float speed()     { return this->spd; }

    // lots of other methods

  protected:

    vec3 pos;
    vec3 dir;
    vec3 upVec;
    vec3 vel;
    float spd;

    // lots of other members

};

我刚刚发现 using namespace 不允许在 class 中,所以我不能这样做。 我只能看到 2 个选项如何摆脱这个,这两个都是愚蠢的:

  1. 在每次使用成员 (vec3, vec4, mat3, ...) 之前重复 namespace_name:: (glm::)
  2. 在 class 之外声明 using namespace 并强制每个人使用这个命名空间,包括我的 header

有没有nicer/cleaner方法,如何解决这个问题?

作为一个好的做法,您自己的 class 也应该在命名空间中。您可以将 using 语句放在那里。

namespace MyProject
{
    using namespace glm;

    class Entity
    {
        ...
    };
}

如果您只是要经常使用 vec3,您可以使用 typedef:

class Entity {
public:
    typedef glm::vec3 vec3;

    Entity(vec3 position, vec3 direction, vec3 upVector, vec3 velocity, float speed = 0.0f);
    // more things...
};

希望对您有所帮助。

如果您查看 this previous question,您可能会对解决此问题的方法有所了解。 我相信大多数人都同意在头文件中定义一个无限范围的命名空间是个坏主意,因为它会影响包含头文件的所有其他文件。 如果允许语法,将 class 和名称空间包含在另一个块中似乎是最好的解决方案。因此,命名空间范围将限于您的外部块。 不幸的是,我已经有一段时间没有认真地进行 c++ 工作了,我不记得编译器是否会在头文件中允许这种语法:

{
using namespace glm;

class Entity {
    ...
}

}