【问题标题】:C restrict with typedefC 使用 typedef 限制
【发布时间】:2011-05-09 16:29:36
【问题描述】:

我现在正在做一些代码,但使用限制关键字遇到了一些问题。

typedef int* pt;

int foo(pt a, pt b)
{
 ... /* stuff */
}

如果我想限制 a 和 b 怎么办?以下代码失败:

typedef int* pt;

int foo(pt restrict a, pt restrict b)
{
 ... /* stuff */
}

提前致谢。

【问题讨论】:

  • 您需要更准确地说“下面的代码失败”是什么意思。
  • FWIW,你的代码用 GCC 编译得很好。

标签: c typedef restrict-qualifier


【解决方案1】:

确保您使用编译器的 C99 标志对其进行编译。 restrict 关键字在 C89 C 中不存在。

【讨论】:

  • 你是指ANSI C99还是ANSI C89?
【解决方案2】:

快速浏览并阅读此类似的SO question,代码将是,因为关键字“restrict”不是 C++ 编译器中的保留关键字,如上述链接中接受的答案所示,__restrict__restricted__,再次检查你的编译器...

typedef int* __restrict pt;

int foo(pt a, pt b)
{
 ... /* stuff */
}

【讨论】:

  • 我在a question 中使用了您的答案,每个人都说这是一个非常糟糕的主意。你能评论我的问题吗?
【解决方案3】:

您需要一个“受限整数指针”int * restrict p 而不是“指向受限整数的指针”restrict int *p,因此您需要创建另一个 typedef。你不能“进入”原来的那个。

编辑:虽然您确实无法进入 typedef 并且修饰符将始终应用于顶层,但在这种情况下,事实证明您 想要 顶层的restrict。这与人们通常使用const 遇到的相反:typedef char *char_ptr 表示const char_ptr(或char_ptr const,它们是等价的)都表示“指向 char 的常量指针”而不是“指向常量 char 的指针”,这就是人们想要。 (另请参阅此 SO 线程:C++ typedef interpretation of const pointers

所以在这种情况下,我认为typedef int *pt 确实意味着restrict pt 意味着int * restrict pt。这很容易验证,因为 gcc 会抱怨 restrict int *x 的“无效使用 'restrict'”,而不是 restrict pt x

【讨论】:

  • 天啊...那我需要很多技巧
  • 你能说清楚吗?为什么 pt restrict 不表示类型 int *restrict ?我认为这个答案是错误的。
  • @Johannes:假设restrict“传播”与const相同,你是对的:static_assert(std::is_same<const pt, int* const>::value, "foobar");没有抱怨。
  • 我在被接受后尝试将其更新为正确,但在答案中指出了问题。对于那些仍然会投反对票的人:至少评论一下你的推理,因为它仍然会在顶部,并且可能会被更新以解决任何问题!
猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 2013-12-23
  • 2016-03-28
  • 2012-06-28
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多