c++ - 将变量定义为自动限制

标签 c++ c++11 auto restrict-qualifier

据我所知,restrict 将指针标记为函数内对特定数据的唯一引用。我通常看到它用在函数参数中,但这似乎也是有益的:

char *restrict a = get_some_string( );
char *restrict b = get_some_other_string( );

(所以编译器知道改变a永远不会改变b,并且可以做额外的优化)。

如果get_some_string返回一个非常复杂的类型,似乎最好使用auto关键字;

auto a = get_some_string( );
auto b = get_some_other_string( );

但是使用 auto restrict 会触发错误“restrict requires a pointer”。那么,我怎样才能将它们结合起来呢?


如评论中所述,restrict 不是 C++ 中的标准关键字;我忘记了我的项目中有一个 #define restrict __restrict__ 行,它在 GCC 中有效。

最佳答案

由于评论中提出了一种解决方案,我将其张贴在这里以供将来引用; (添加使其健壮)

typename std::remove_reference<decltype(get_some_string()[0])>::type *restrict a = get_some_string( );

太可怕了。在这些情况下,我将坚持使用 typedef,但我可以想象在某些情况下可能需要这样的行为。使用宏,它变得不那么可怕了:

#define decltype_restrict(x) typename std::remove_reference<decltype((x)[0])>::type *restrict
decltype_restrict(get_some_string()) a = get_some_string( );

关于c++ - 将变量定义为自动限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17305039/

相关文章:

c++ - 是否可以有一个 "auto"成员变量?

c# - 将 IWICStream/IStream 从非托管 C++ DLL 返回到托管 C# 并读取它

c++ - 为什么我的 fstream 被隐式删除了?

c++ - 奇怪的 poco react 器的通知

c++ - 编译器如何选择给 auto 赋值?

c++ - 错误 : call to implicitly-deleted copy constructor of unique_ptr with auto

c++ - 相交三角形的面积

c++ - 给出了在 C++ 中返回对象的各种方法,这些 return 语句中的每一个的潜在问题是什么

c++ - 鉴于 C++ 中没有反射,我怎样才能使它更健壮?

c++ - 在编译时测试字节序 : is this constexpr function correct according to the standard?