什么叫做函数运行于compile-time?非常简单,说的就是一个函数代码由编译器编译成机器代码,且直接在compile-time执行,我们知道函数有传参,如果参数在compile-time就知道了,那么函数在compile-time执行也就变得可能,假设参数只有少部分可以在compile-time所知,那么函数可能只有部分在compile-time执行
const
:
static member function或者member data就是class里面定义的成员变量或者函数前面加上static关键字,不论class实例化多少次经此一份,且static member function/data没有this指针,可以在class外部直接访问和初始化,而non-static member function相反,只能由class对象初始化,如下
#include
using namespace std; struct X { private: int i; static int si; //static member data public: void set_i(int arg) { i = arg; } static void set_si(int arg) { si = arg; } void print_i() { //non-static member function cout << "Value of i = " << i << endl; cout << "Again, value of i = " << this->i << endl; } static void print_si() { //static member function cout << "Value of si = " << si << endl; cout << "Again, value of si = " << this->si << endl; // error } }; int X::si = 77; // Initialize static data member int main() { X xobj; xobj.set_i(11); xobj.print_i(); // static data members and functions belong to the class and // can be accessed without using an object of class X X::print_si(); X::set_si(22); X::print_si(); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
constexpr
:
constexpr
上面介绍了,constexpr 变量是compile-time,而constexpr 函数则是询问编译器,这个constexpr函数可否在compile-time执行,如果可以最好,不行就放到run-time执行,constexpr是C++ 11的特性consteval
首先要说明的是consteval是c++ 20的标准,并且consteval不能声明变量,换句话说consteval只能声明函数,且consteval函数是告诉编译器,将这个函数放到compile-time执行,如果不行就直接报错constexpr int foo (int x) { return x; }
consteval int bar (int x) { return x; } //一定会在compile-time中执行,否则就报错
consteval int v1 = 5; //error!!!
int main(){
foo(42);
int i = 5;
foo(5);
bar(42);
bar(i);
}