Constant Expressions with constexpr

Contents[Show]

You can define with the keyword constexpr an expression that can be evaluated at compile time. constexpr can be used for variables, functions, and user-defined types. An expression that is evaluated at compile time has a lot of advantages. For example constexpr variables and instances of user-defined types are automatically thread-safe and can be stored in ROM; constexpr functions that are evaluated at compile time, are totally done with their work at run time.

All done at compile time

I already have indicated it in my post User-defined literals.  The calculation how many kilometers per week I drive on average has a massive optimization potential. In this post I will solve my promise. To make it easy for you. Here is the program from the post User-defined literals once more.

 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
76
77
78
79
80
// userdefinedLiterals.cpp

#include <iostream>

namespace Distance{

  class MyDistance{
    public:
      MyDistance(double i):m(i){}

      friend MyDistance operator+(const MyDistance& a, const MyDistance& b){
        return MyDistance(a.m + b.m);
      }
      friend MyDistance operator-(const MyDistance& a,const MyDistance& b){
        return MyDistance(a.m - b.m);
      }
	  
      friend MyDistance operator*(double m, const MyDistance& a){
        return MyDistance(m*a.m);
}
friend MyDistance operator/(const MyDistance& a, int n){ return MyDistance(a.m/n); } friend std::ostream& operator<< (std::ostream &out, const MyDistance& myDist){ out << myDist.m << " m"; return out; } private: double m; }; namespace Unit{ MyDistance operator "" _km(long double d){ return MyDistance(1000*d); } MyDistance operator "" _m(long double m){ return MyDistance(m); } MyDistance operator "" _dm(long double d){ return MyDistance(d/10); } MyDistance operator "" _cm(long double c){ return MyDistance(c/100); } } } Distance::MyDistance getAverageDistance(std::initializer_list<Distance::MyDistance> inList){ auto sum= Distance::MyDistance{0.0}; for (auto i: inList) sum = sum + i ; return sum/inList.size(); } using namespace Distance::Unit; int main(){ std:: cout << std::endl; auto work= 63.0_km; auto workPerDay= 2 * work; auto abbrevationToWork= 5400.0_m; auto workout= 2 * 1600.0_m; auto shopping= 2 * 1200.0_m; auto distPerWeek1= 4*workPerDay-3*abbrevationToWork+ workout+ shopping; auto distPerWeek2= 4*workPerDay-3*abbrevationToWork+ 2*workout; auto distPerWeek3= 4*workout + 2*shopping; auto distPerWeek4= 5*workout + shopping; auto averageDistance= getAverageDistance({distPerWeek1,distPerWeek2,distPerWeek3,distPerWeek4}); std::cout << "averageDistance: " << averageDistance << std::endl; std::cout << std::endl; }

 

How can I massively improve the program? Quite easy by using constexpr. My key idea is it to declare all instances of MyDistance in the main program as constexpr. Therefore, I say to the compiler: Instantiate the objects at compile time. But the compiler can only perform its job if the instantiation is based on constant expressions. If the compiler can not do it, I will get a compiler error.

 

 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
76
77
78
79
80
81
// userdefinedLiteralsConstexpr.cpp

#include <iostream>

namespace Distance{

  class MyDistance{
    public:
      constexpr MyDistance(double i):m(i){}

      friend constexpr MyDistance operator+(const MyDistance& a, const MyDistance& b){
        return MyDistance(a.m + b.m);
      }
      friend constexpr MyDistance operator-(const MyDistance& a,const MyDistance& b){
        return MyDistance(a.m - b.m);
      }
	  
      friend constexpr MyDistance operator*(double m, const MyDistance& a){
        return MyDistance(m*a.m);
      }
	  
      friend constexpr MyDistance operator/(const MyDistance& a, int n){
        return MyDistance(a.m/n);
      }
	  
      friend std::ostream& operator<< (std::ostream &out, const MyDistance& myDist){
        out << myDist.m << " m";
        return out;
      }
    private:
double m; }; namespace Unit{ constexpr MyDistance operator "" _km(long double d){ return MyDistance(1000*d); } constexpr MyDistance operator "" _m(long double m){ return MyDistance(m); } constexpr MyDistance operator "" _dm(long double d){ return MyDistance(d/10); } constexpr MyDistance operator "" _cm(long double c){ return MyDistance(c/100); } } } constexpr Distance::MyDistance getAverageDistance(std::initializer_list<Distance::MyDistance> inList){ auto sum= Distance::MyDistance{0.0}; for (auto i: inList) sum = sum + i ; return sum/inList.size(); } using namespace Distance::Unit; int main(){ std:: cout << std::endl; constexpr auto work= 63.0_km; constexpr auto workPerDay= 2 * work; constexpr auto abbrevationToWork= 5400.0_m; constexpr auto workout= 2 * 1600.0_m; constexpr auto shopping= 2 * 1200.0_m; constexpr auto distPerWeek1= 4*workPerDay-3*abbrevationToWork+ workout+ shopping; constexpr auto distPerWeek2= 4*workPerDay-3*abbrevationToWork+ 2*workout; constexpr auto distPerWeek3= 4*workout + 2*shopping; constexpr auto distPerWeek4= 5*workout + shopping; constexpr auto averageDistance= getAverageDistance({distPerWeek1,distPerWeek2,distPerWeek3,distPerWeek4}); std::cout << "averageDistance: " << averageDistance << std::endl; std::cout << std::endl; }

 

The result of the calculation is not so exciting. To compile the program I have to use a C++14 compiler. A current GCC of clang is fine. The current Microsoft Visual 2015 C++-Compiler supports only C++11. Therefore, cl.exe will not compile the function getAverageDistance. In C++11 a constexpr function can only have a return statement.

userdefinedLiteralsConstexprResult

But it is very exciting to look at the assembler instructions. To make my job easy I use the interactive compiler hosted on https://gcc.godbolt.org/. Have I already mentioned that I like this tool very much?

 userdefinedLiteralsConstexpr

 

How should we interpret the results? Quite easy. The in the main program (line 64 - 75) defined constant expressions are part of the assembler program. Or to say it differently. All calculations are done at compile time. At run time the program consists only of the already calculated expressions. That is an extremely easy job for the run time.

What's next?

So, that's enough to make you keen on more. The details will follow in the next post. I will have a deeper look into constexpr variables, functions, and user-defined types. You have to keep a few rules in mind. Firstly, C++14 constexpr functions are more powerful than C++11 constexpr functions. Secondly, you can execute constexpr functions at run time. Lastly, there a few restrictions for user-defined types to instantiate them at compile time.

 

 

 

 

 

 

 

 

title page smalltitle page small Go to Leanpub/cpplibrary "What every professional C++ programmer should know about the C++ standard library".   Get your e-book. Support my blog.

 

Tags: constexpr

Comments   

0 #1 TanDo 2016-11-23 04:13
"Firstly, C++14 constexpr functions are more powerful than C++ constexpr functions"
I think you miss the word: powerful than C++ 11 constexpr
Quote
0 #2 Rainer Grimm 2016-11-23 07:29
Quoting TanDo:
"Firstly, C++14 constexpr functions are more powerful than C++ constexpr functions"
I think you miss the word: powerful than C++ 11 constexpr

Thanks, I will fix it.
Quote

Add comment


My Newest E-Book

Latest comments

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 559

All 255864

Currently are 355 guests and no members online