0.Array
int url[10]; //true
int url[6 + 4] //true
int len = 10;
int url[len] //flase
1.Constexpr
#include <iostream>
using namespace std;
int main()
{
/*
* If have not constexpr, CPP throw error
*/
constexpr int num = 1 + 2 + 3;
int url[num] = {1,2,3,4,5,6};
couts<< url[1] << endl;
return 0;
}
2.Only have one ‘return’
# Error
constexpr int display(int x) {
int ret = 1 + 2 + x;
return ret;
}
# True
constexpr int display(int x) {
return 1 + 2 + x;
}
3.Must have ‘return’
# Error
constexpr void display() {
...
}
# True
constexpr int display() {
...
}
4.Must have funciion declaration
#include <iostream>
using namespace std;
int noconst_dis(int x);
// constexpr
constexpr int display(int x);
constexpr int display(int x){
return 1 + 2 + x;
}
int main()
{
int a[display(3)] = { 1,2,3,4 };
cout << a[2] << endl;
cout << noconst_dis(3) << endl;
return 0;
}
int noconst_dis(int x) {
return 1 + 2 + x;
}
5.‘Return’ must constant expession
#include <iostream>
using namespace std;
int num = 3;
constexpr int display(int x){
return num + x;
}
int main()
{
//display(3) not is constant
int a[display(3)] = { 1,2,3,4 };
return 0;
}
6.Constexpr struct
# Error
#include <iostream>
using namespace std;
constexpr struct myType {
const char* name;
int age;
};
int main()
{
constexpr struct myType mt { "zhangsan", 10 };
cout << mt.name << " " << mt.age << endl;
return 0;
}
# True
#include <iostream>
using namespace std;
struct myType {
constexpr myType(char *name,int age):name(name),age(age){};
const char* name;
int age;
};
int main()
{
constexpr struct myType mt { "zhangsan", 10 };
cout << mt.name << " " << mt.age << endl;
return 0;
}
7. CLass
#include <iostream>
using namespace std;
//自定义类型的定义
class myType {
public:
constexpr myType(const char *name,int age):name(name),age(age){};
constexpr const char * getname(){
return name;
}
/*
* unsupport virtual function
*/
constexpr int getage(){
return age;
}
private:
const char* name;
int age;
//其它结构体成员
};
int main()
{
constexpr struct myType mt { "zhangsan", 10 };
constexpr const char * name = mt.getname();
constexpr int age = mt.getage();
cout << name << " " << age << endl;
return 0;
}
8.Template
#include <iostream>
using namespace std;
struct myType {
const char* name;
int age;
};
template<typename T>
constexpr T dispaly(T t){
return t;
}
int main()
{
struct myType stu{"zhangsan",10};
struct myType ret = dispaly(stu);
cout << ret.name << " " << ret.age << endl;
constexpr int ret1 = dispaly(10);
cout << ret1 << endl;
return 0;
}