Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template metaprogramming: constexpr function

I was watching Bjarne Stroustrup's talk "The Essential C++".

In Q&A session, on how to manage heavy template programming codes, he mentioned that: "by constack perfunction you can eliminate essentially every template metaprogramming that generates a value by writting ordinary code".

The constack perfunction is just a wild guess by the sound.

May I ask what is the correct term for that technology? so that I could do some follow up reading.

update: just modify the title to "constexpr function".

like image 801
athos Avatar asked Mar 18 '23 11:03

athos


1 Answers

constexpr functions, added in C++11, can be evaluated at compile-time and be used as template arguments in template metaprogramming. In C++11 they are very limited and can (nearly) only consist of a single return expression. C++14 makes them less restrictive.

For example this is possible:

constexpr std::size_t twice(std::size_t sz) {
    return 2 * sz;
}

std::array<int, twice(5)> array;

Whereas before C++11, template 'hacks' were needed, like for instance:

template<std::size_t sz>
class twice {
public:
    static const std::size_t value = 2 * sz;
}

std::array<int, twice<5>::value> array;

It can for instance be used to generate values (like math constants, trigonometric lookup tables, ...) at compile-time in a clean manner.

like image 76
tmlen Avatar answered Mar 20 '23 02:03

tmlen