C++11的constexpr

1、作用

用于代表后续函数、变量、表达式是常量的

2、修饰变量

constexpr 修饰变量,从而使该变量获得在编译阶段即可计算出结果的能力。

#include <iostream>
using namespace std;

int main()
{
    constexpr int num = 1 + 2 + 3;
    int url[num] = {1,2,3,4,5,6};
    couts<< url[1] << endl; //2
    return 0;
}

3、修饰函数

constexpr 还可以用于修饰函数的返回值,这样的函数又称为“常量表达式函数”,这个函数需要满足:

①、只能包含一条 return 返回语句;

②、该函数必须有返回值,即函数的返回值类型不能是 void;

③、常量表达式函数与普通函数不同,调用位置之前必须要有该函数的定义,否则会导致程序编译失败;

④、return 返回的表达式必须是常量表达式。

#include <iostream>
using namespace std;

int num = 3;
constexpr int display(int x){
    return num + x;
}
int main()
{
    //调用常量表达式函数
    int a[display(3)] = { 1,2,3,4 };
    return 0;
}

4、修饰类的构造函数

onstexpr 修饰类的构造函数时,要求该构造函数的函数体必须为空,且采用初始化列表的方式为各个成员赋值时,必须使用常量表达式

5、修饰模板函数

 constexpr 修饰的模板函数实例化结果不满足常量表达式函数的要求,则 constexpr 会被自动忽略,即该函数就等同于一个普通函数

如:

template<typename _Tp>
constexpr typename std::remove_reference<_Tp>::type&&
move(_Tp&& __t) noexcept
{ return static_cast<typename std::remove_reference<_Tp>::type&&>(__t); }

参考:http://c.biancheng.net/view/7781.html




长风破浪会有时,直挂云帆济沧海!
可通过下方链接找到博主
https://www.cnblogs.com/judes/p/10875138.html
原文地址:https://www.cnblogs.com/judes/p/15338416.html