c++ constexpr用法

#include <string>
#include <iostream>
#include <vector>
#include <array>
using namespace std;
class A {
public:
    // constexpr A(int a) : _a(a) {}
    constexpr A() : _a(0) {}
    constexpr A(int a) : _a(a) {}
    constexpr int getValue() const noexcept { return _a; } 
    constexpr void setValue(int a) noexcept { _a = a;  } 
private:
    int _a;
};
constexpr
int func(const int &a)
{
    // static int a1 = 1; //  'a1' declared 'static' in 'constexpr' function
	// g_a++;  // the value of 'g_a' is not usable in a constant expression
    return a+1;
}
constexpr 
A reflection(const A& p) noexcept
{
    A result;
    result.setValue(p.getValue() + 2);
    return result;
}
int main(void) 
{
	/* 数组的尺寸规格必须是常量表达式 */
	cout << "----------------" << endl;
    constexpr auto arraySize = 10;
    array<int, arraySize> data;
    cout << sizeof(data) << endl;

    cout << "----------------" << endl;
    int a = 10;
    // std::array<int, func(a)> data2;  // error 需要传入常量表达式 否则返回的不是常量表达式
    array<int, func(arraySize)> data2;
    cout << sizeof(data2) << endl;
    
    cout << "----------------" << endl;
    constexpr A a2(5);   
    /*
		A的构造函数被声明成了 constexpr 函数, 由千传入它的实参在编译期可
		知,构造出来的 A 对象的数据成员,其值也是在编译期可知的。如此初始化出来
		的 A 对象,也自然具备了 constexpr 属性。
	*/
	/*
		访问器 getValue 也可以声明为 constexpr, 原因在于,若它们是通
		过一个在编译期已知其值的 A 对象,即一个 constexpr A 对象来调用的话,
		数据成员 _a 的值就可以在编译期获知。从而,就能够撰写出这样的 constexpr 函数,
		它调用 A 的访问器并使用其返回结果来初始化 constexpr 对象:
	*/
     /* constexpr A a3(a);  构造函数需要加constexpr修饰  需要传入常量表达式*/
    array<int, func(a2.getValue())> data3;
    /* func reflection getValue 均返回常量表达式 所以正确 */
    array<int, func(reflection(a2).getValue())> data4; 
    cout << sizeof(data3) << endl;
    cout << sizeof(data4) << endl;
}
/*
	输出信息
	----------------
	40
	----------------
	44
	----------------
	24
	32
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值