c++ - 在 C++ 命名空间中使用内置类型(double、int 等)?

标签 c++ namespaces typedef swig built-in

我能否使 intdouble 等内置类型在 C++ 命名空间中可用?

#include <complex>

typedef int my_int;

namespace my_namespace {
  namespace std = ::std;  // Works
  using ::my_int;         // Works

  using ::int;            // Fails: "expected unqualified-id before 'int'"
  typedef ::int int;      // Fails: "expected unqualified-id before 'int'"
}

typedef int out::int;     // Fails: "expected unqualified-id before 'int'"

my_namespace::my_int x;            // Works
my_namespace::std::complex<int> c; // Works

// I would like to use this:
my_namespace::int x2;    // Fails: "expected unqualified-id before 'int'" 

我怀疑这是由于语言限制禁止使用带有关键字的限定标识符(在本例中为 int),但我希望有一些方法可以公开这些。

用例

我正在尝试使用 namespace 来组织类型,以便外部工具 ( SWIG) 可以适本地用另一种语言包装函数。例如:

void one_two(int &x, int &y) { x = 1; y = 2; }

在目标语言中,这可以包装为一个改变其参数 one_two(x, y) 的函数,或者返回输出 x, y = one_two() 的函数。我想要某种方式来“注释”参数以提供 SWIG与预期用途。当前最干净的选项 SWIG实现是使用命名空间来区分这两种用途:因此输出版本 x, y = one_two() 可以表示为::

void one_two(out::int &x, out::int &y) { x = 1; y = 2; }

如果我能以某种方式使 out::int 成为 int 的同义词。 (这种方法适用于用户定义的类型。)

最佳答案

int 和 friends 是语言中的关键字。它们不是全局 namespace 中的名称;就语言而言,它们根本不是名字。用 :: 限定它们是错误的。尝试将任何变量命名为 int 也是一个错误。具体见C++03中的2.1 paragraph 1,C++11中的2.12 paragraph 1(文同):

The identifiers shown in Table 3 are reserved for use as keywords (that is, they
are unconditionally treated as keywords in phase 7):
[ ... ]
int

关于c++ - 在 C++ 命名空间中使用内置类型(double、int 等)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11698224/

相关文章:

python - 如何动态构造闭包的命名空间 "pythonically"

c++ - 在类中声明一个枚举

c - typedef string c 赋值给位置

c++ - 向 typedef 添加函数

c++ - 如何使用带有 libcurl 的 HTTP 在 C/C++ 中上传文件?

c++ - 如果我将一个 POD 结构分配给另一个 POD 结构,是否存在内存泄漏?

c++ - 如何显示命名空间中的所有元素?

c++ - 为什么 fmod 会产生不同的结果?

c++ - Gcc 隐藏来自包含的静态库的符号的可见性

c++ - 头文件中的 typedef vector size_type