-
Notifications
You must be signed in to change notification settings - Fork 0
/
constinit_consteval_demos.cpp
75 lines (53 loc) · 2.15 KB
/
constinit_consteval_demos.cpp
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// Demonstrates MSVC implementations for
// Adding the constinit keyword : https://wg21.link/P1143R2
// Immediate functions(consteval) : https://wg21.link/P1073R3
#include <iostream>
consteval int myConstEvalFunction(int n) {
return 10 * n;
}
void consteval_demo()
{
std::cout << "\nconsteval demo:\n";
std::cout << myConstEvalFunction(1) << std::endl;
const int i = 2;
std::cout << myConstEvalFunction(i) << std::endl;
// Still OK
std::cout << myConstEvalFunction(myConstEvalFunction(i)) << std::endl;
// This will return an error if compiled because invoking a consteval function that does not produce a constant expression is ill-formed
//int j = 3;
//std::cout << myConstEvalFunction(j) << std::endl;
}
// Using the example from the constinit proposal
const char* g() { return "Dynamic initialization"; }
constexpr const char* f(bool isConstantInit) {
return isConstantInit ? "Constant initializater" : g();
}
// Builds OK
constinit const char* constInitFunc = f(true);
// Fails: illegal initialization of 'constinit' entity with a non-constant expression
//constinit const char* dynamicInitFunc = f(false);
// Builds OK, globals have static storage duration
constinit int globalConstInitValue;
void constinit_demo()
{
std::cout << "\nconstinit demo:\n";
std::cout << "constInitFunc: " << constInitFunc << std::endl;
std::cout << "globalConstInitValue: " << globalConstInitValue << std::endl;
// Builds OK
static constinit const char* staticConstInitVal = f(true);
std::cout << "staticConstInitVal: " << staticConstInitVal << std::endl;
// Build error: constinit is only allowed on a variable declaration with static or thread storage duration
// constinit const char* nonStaticConstInitVal = f(true);
// This will also fail to build because it's neither static nor thread storage
//constinit int localConstInit;
// Builds OK
constinit static int staticLocalConstInitValue;
std::cout << "staticLocalConstInitValue: " << staticLocalConstInitValue << std::endl;
}
void consteval_and_constinit_demo()
{
//consteval_demo();
constinit_demo();
}