- constexpr
C++ 11引入constexpr ,但有很多限制,比如不能用于set成员函数/不能有if-else for循环等语句/只能有一个return语句/除了构造函数修饰的成员函数返回值不能为void等。后面解除了这些限制
C++17新支持了constexpr lambda表达式
建议尽量多使用constexpr 以提高程序性能
注意:constexpr修饰的函数只有赋值给constexpr变量(构造函数除外),才能确保为编译时运行
举例:
#include <iostream>
using namespace std;
class Foo
{
public:
constexpr explicit Foo(int i) : _i(i) {}
constexpr int getValue() const
{
return _i;
}
constexpr int valuePlusOne()
{
_i = _i + 1;
return _i;
}
private:
int _i;
};
int main()
{
printf("__cplusplus is %d \n", __cplusplus);
constexpr Foo foo(1);// 编译时:
printf("foo is %d", foo.getValue()); //运行时 第一行打印为1
foo.valuePlusOne();//Run Time
printf("foo is %d", foo.getValue());//运行时 第二行打印为2
constexpr int v = foo.getValue();// 编译时 说明constexpr修饰的函数只有赋值给constexpr变量(构造函数除外),才能确保为编译时运行
printf("v is %d", v);// 编译时 第三行输出为1
static_assert(foo.getValue() == 1, "a");// 无报错
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。