C ++ 11中的纯函数 [英] Pure functions in C++11

查看:70
本文介绍了C ++ 11中的纯函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11中的某个人可以在 gcc 中以某种方式将一个函数(不是类方法)标记为 const 来表明它是并且不使用全局内存,而仅使用其参数?

Can one in C++11 somehow in gcc mark a function (not a class method) as const telling that it is pure and does not use the global memory but only its arguments?

我已经尝试过 gcc __ attribute __((const)),这正是我想要的精确.但是在函数中触摸全局内存时,它不会产生任何编译时错误.

I've tried gcc's __attribute__((const)) and it is precisely what I want. But it does not produce any compile time error when the global memory is touched in the function.

编辑1

请小心.我的意思是纯函数.非恒定功能.GCC的属性有点令人困惑.纯函数仅使用其参数.

Please be careful. I mean pure functions. Not constant functions. GCC's attribute is a little bit confusing. Pure functions only use their arguments.

推荐答案

您是否在寻找 constexpr ?这告诉编译器该函数可以在编译时进行评估. constexpr 函数必须具有文字返回值和参数类型,并且主体只能包含静态断言,typedef,使用声明和指令以及一个return语句.可以在常量表达式中调用 constexpr 函数.

Are you looking for constexpr? This tells the compiler that the function may be evaluated at compile time. A constexpr function must have literal return and parameter types and the body can only contain static asserts, typedefs, using declarations and directives and one return statement. A constexpr function may be called in a constant expression.

constexpr int add(int a, int b) { return a + b; }

int x[add(3, 6)];


看过 __ atribute __((const))的含义,答案是否定的,您不能使用标准C ++做到这一点.使用 constexpr 将达到相同的效果,但是只在功能有限得多的一组函数上.但是,只要编译的程序以相同的方式运行(假设规则),就不会阻止编译器自行进行这些优化.


Having looked at the meaning of __atribute__((const)), the answer is no, you cannot do this with standard C++. Using constexpr will achieve the same effect, but only on a much more limited set of functions. There is nothing stopping a compiler from making these optimizations on its own, however, as long as the compiled program behaves the same way (the as-if rule).

这篇关于C ++ 11中的纯函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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