C/C++ __限制类型
有没有一种方法可以使用 typedef 整型/浮点类型来定义,这意味着没有别名?
相当于(但原始构造):
template < typename T >
struct restrict { T* __restrict data; };
作为相关问题,是否可以询问 gcc 它确定指针的别名/无别名是什么?
Is there a way to define using typedef integral/float type which implies no aliasng?
something equivalent to (but primitive construct):
template < typename T >
struct restrict { T* __restrict data; };
as related question, is it possible to ask gcc what it determines alias/no alias of pointer is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如评论中所指出的,许多较新的 C++ 编译器确实支持限制类型限定符的 C99 实现。由于
restrict
不是C++中的保留关键字,因此编译器通常使用__restrict
或__restrict__
。 GCC 和 Visual C++ 很好地记录了这一点,并明确引用了 C99。C++ 1998 标准规定“
typedef
说明符不得...在 decl-specifier-seq 中与除 type- 之外的任何类型的说明符组合”说明符。”本质上,它必须是一个类型说明符列表,其中包括两个cv限定符,const
和易失性
。C99 类似地定义了 typedef,只不过它的限定符列表包括
restrict
。预期 typedef 中对非标准 __restrict 的类似支持似乎是合理的......但你永远不知道!
一个聪明而简单的测试方法如下:
这只是利用了这样一个事实:如果在目标文件中找到未解析的
link_fail
符号,链接器将抛出错误。如果编译器正确限制了这两个参数,那么它应该知道a
的值,即使在b
更改之后也是如此。因此,它应该从生成的目标文件中删除整个 if 块,因为它永远不会运行。请注意,尽管 GCC 至少从 3.0 版本开始就支持限制语法,但直到 版本 4.5。
As noted in the comments, many newer C++ compilers do support the C99 implementation of the restrict type qualifier. Since
restrict
is not a reserved keyword in C++, the compilers generally use__restrict
or__restrict__
. Both GCC and Visual C++ document this nicely, with explicit references to C99.The C++ 1998 standard states that "The
typedef
specifier shall not ... be combined in a decl-specifier-seq with any kind of specifier except a type-specifier." Essentially, it must be a list of type-specifiers, which includes the two cv-qualifiers,const
andvolatile
.C99 defines typedef similarly, except that its list of qualifiers includes
restrict
.It would seem reasonable to anticipate similar support in typedefs for the nonstandard
__restrict
... but you never know!A clever and easy way to test this is as follows:
This simply exploits the fact that if the unresolved
link_fail
symbol is found in the object file, the linker will throw an error. If the compiler is properly restricting the two arguments, then it should know the value ofa
, even afterb
is changed. Thus, it should strip the entire if block from the generated object file since it will never be run.Note that although GCC supported the restrict syntax since at least version 3.0, it really didn't perform the proper optimizations until version 4.5.