【问题标题】:Using builtin types (double, int, etc.) in a C++ namespace?在 C++ 命名空间中使用内置类型(double、int 等)?
【发布时间】:2012-07-28 04:17:24
【问题描述】:

我可以在 C++ 命名空间中提供像 intdouble 这样的内置类型吗?

#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),但我希望有某种方式可以公开这些。

用例

我正在尝试使用命名空间来组织类型,以便外部工具 (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 的同义词。 (这种方法适用于用户定义的类型。)

【问题讨论】:

  • 您在此处使用 SWIG 定位什么语言?许多目标语言都可以很容易地在界面中插入这种“强类型定义”。
  • @Flexo:Python,但我看不出这有什么帮助。目标是可以自动包装的 C++ 代码。我需要为 SWIG 提供线索 - 所以要么修改名称(OUTPUT 而不是 x,这不是由于 kwargs 而不可取的)或使用 typedef。 out 命名空间很干净,但如果它也适用于内置类型会更好,我认为这是不可能的。见this thread

标签: c++ namespaces typedef swig built-in


【解决方案1】:

int 和朋友是语言中的关键字。它们不是全局命名空间中的名称;就语言而言,它们根本不是名称。用:: 限定它们是错误的。试图命名任何变量int 也是一个错误。具体见C++03中的2.1第1段,C++11中的2.12第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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多