将命名空间赋予 C++ 中的现有库

Give namespace to an existing library in C++

C++ 中的某些库不像 stl 那样使用名称空间。与 ncurses 一样,可以在没有命名空间的情况下调用那里可用的函数。它具有可以全局访问的 move () 功能。现在,我将 ncurses 库放入我的 class 文件中,该文件将具有 move 函数作为其成员函数。如果我这样写 class:

#include <ncurses.h>

class MyClass {
    public:
        void move (int x, int y) {
            // moving
        }
        void do_something (int x, int y) {
            move (x, y);
            // do something
        }
}

我不知道 MyClass 会调用哪个 move () 函数。我认为如果可以给 ncurses 库一个命名空间,问题就会消失,所以可以使用(例如)ncurses::move () 而不仅仅是 move ()。是否可以给它命名空间?如果不是,如果你发现类似这样的东西(当然不是更改函数名称)你会怎么做?

I don't know which move () function will be called by MyClass.

成员函数,因为它在较窄的范围内。非限定名称查找从本地范围开始并向外工作,直到找到匹配项。所以在这里它会在函数的块范围内查找;然后搬出去class;然后找到 MyClass::move 并停在那里。它不会考虑 class.

之外的全局命名空间

Is it possible to give it namespace?

您可以将名称限定为 ::move 以指定全局命名空间。

在这种情况下,您可以完全限定调用,而不是依赖基本上找到 "nearest" 匹配项的名称查找,如下所示:

::move(x, y);

这将在顶层查找 move,找到 ncurses,no-namespace,版本。

用于添加 ncurses 命名空间,不是真的。你可以试试:

namespace ncurses {
#include <ncurses.h>
}

但这真的很糟糕,几乎肯定无法正常工作。另一种方法是创建一个包装器 header,手动将您感兴趣的所有函数添加到命名空间中,例如:

// wrapped_ncurses.h
#ifndef WRAPPED_NCURSES_H
#define WRAPPED_NCURSES_H
#include <ncurses.h>
namespace ncurses {
    using ::move;
}
#endif

当然,您可以根据需要为整个库创建一个 C++ 包装器 (or try to find an existing one)。