C 用 typedef 限制 [英] C restrict with typedef

查看:33
本文介绍了C 用 typedef 限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在做一些代码并且在使用restrict关键字时遇到了一些问题.

typedef int* pt;int foo(pt a, pt b){.../* 东西 */}

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

typedef int* pt;int foo(pt 限制 a, pt 限制 b){.../* 东西 */}

提前致谢.

解决方案

你需要一个限制整数的指针"int *restrict p 而不是限制整数的指针" restrict int*p 所以你需要制作另一个 typedef.你无法进入"原来的那个.

虽然您不能到达typedef内部并且修饰符将始终应用于顶级,但在这种情况下,事实证明您想要 顶层的 restrict.这与人们通常使用 const 遇到的情况相反:typedef char *char_ptr 表示 const char_ptr(或 char_ptr const,它们是等价的)都意味着指向字符的常量指针"而不是人们想要的指向常量字符的指针".(另请参阅此 SO 线程:C++ typedef 解释常量指针)>

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

i'm doing some code now and got some problem using restrict keyword.

typedef int* pt;

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

What if I want to make a and b restricted? The code below failed:

typedef int* pt;

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

Thanks in advance.

解决方案

You need a "restricted pointer to integer" int * restrict p not a "pointer to restricted integer" restrict int *p so you will need to make another typedef. You can't "reach inside" the original one.

EDIT: While it's true that you can't reach inside the typedef and the modifier will always apply at the top level, in this case it turns out that you want the restrict at the top level. It's the inverse of what people usually run into with const: typedef char *char_ptr means const char_ptr (or char_ptr const, they're equivalent) both mean "constant pointer to char" not "pointer to constant char" which is what people want. (See also this SO thread: C++ typedef interpretation of const pointers )

So in this case I think typedef int *pt does mean that restrict pt means int * restrict pt. It's pretty easy to verify because gcc will complain about "invalid use of 'restrict'" for restrict int *x but not for restrict pt x.

这篇关于C 用 typedef 限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆