c++11 常量表達式


c++11 常量表達式

 

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
#include <vector>
#include <map>

/**
 * 常量表達式主要是允許一些計算發生在編譯時,即發生在代碼編譯而不是運行的時候。
 * 這是很大的優化:假如有些事情可以在編譯時做,它將只做一次,而不是每次程序運行時都計算。
 */

/*
constexpr函數的限制:
函數中只能有一個return語句(有極少特例)
函數必須返回值(不能是void函數)
在使用前必須已有定義
return返回語句表達式中不能使用非常量表達式的函數、全局數據,且必須是一個常量表達式
*/
constexpr int GetConst()
{
    return 3;
}
//err,函數中只能有一個return語句
constexpr int data()
{
    constexpr int i = 1;
    return i;
}
constexpr int data2()
{
    //一個constexpr函數,只允許包含一行可執行代碼
    //但允許包含typedef、 using 指令、靜態斷言等。
    static_assert(1, "fail");
    return 100;
}

int a = 3;
constexpr int data3()
{
    return a;//err, return返回語句表達式中不能使用非常量表達式的函數、全局數據
}

/*
常量表達式的構造函數有以下限制:
函數體必須為空
初始化列表只能由常量表達式來賦值
*/
struct Date
{
    constexpr Date(int y, int m, int d): year(y), month(m), day(d) {}

    constexpr int GetYear() { return year; }
    constexpr int GetMonth() { return month; }
    constexpr int GetDay() { return day; }

private:
    int year;
    int month;
    int day;
};


void mytest()
{
   int arr[GetConst()] = {0};
   enum {e1 = GetConst(), e2};

   constexpr int num = GetConst();

   constexpr int func(); //函數聲明,定義放在該函數后面
   constexpr int c = func();  //err, 無法通過編譯, 在使用前必須已有定義

   constexpr Date PRCfound {1949, 10, 1};
   constexpr int foundmonth = PRCfound.GetMonth();
   std::cout << foundmonth << std::endl;  // 10

    return;
}

constexpr int func()
{
    return 1;
}


int main()
{
    mytest();

    system("pause");
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM