Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a constexpr function to be evaluated at compile time [duplicate]

Given the following code:

constexpr int omg() { return 42; }

const int a = omg(); // NOT guaranteed to be evaluated at compile time

constexpr const int a = omg(); // guaranteed to be evaluated at compile time

Is there a way to force something to be evaluated at compile time without assigning it to something constexpr (or in a compile time context like a template parameter ot enum shenanigans)?

Something like this:

const int a = force_compute_at_compile_time(omg());

perhaps something like this (which doesn't compile - I'm not much into constexpr yet):

template<typename T> constexpr T force_compute_at_compile_time(constexpr const T& a) { return a; }
like image 742
onqtam Avatar asked Oct 06 '16 07:10

onqtam


1 Answers

You could use non-type template arguments:

template <int N> constexpr int force_compute_at_compile_time();

const int a = force_compute_at_compile_time<omg()>();

Since N is a template argument, it has to be a constant expression.

like image 109
TartanLlama Avatar answered Oct 02 '22 19:10

TartanLlama