Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ constexpr at compile time

Am I right to think that this function should only be evaluated at compile time, or is there a run-time cost to it?

template <typename T>
size_t constexpr CompID() {
    return typeid(T).hash_code();
}

struct Foo {};

int main(int argc, const char * argv[]) {
    size_t foo = CompID<Foo>();
    return 0;
}
like image 953
sharvey Avatar asked Oct 08 '12 16:10

sharvey


People also ask

Is constexpr evaluated at compile time?

A constexpr function is one whose return value is computable at compile time when consuming code requires it. Consuming code requires the return value at compile time to initialize a constexpr variable, or to provide a non-type template argument.

Is constexpr faster?

Not only will your code be faster and smaller, it'll be safer. Code marked constexpr can't bitrot as easily.

What does constexpr mean in C++?

The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time. Such variables and functions can then be used where only compile time constant expressions are allowed (provided that appropriate function arguments are given).

When to use #define vs constexpr?

#define directives create macro substitution, while constexpr variables are special type of variables. They literally have nothing in common beside the fact that before constexpr (or even const ) variables were available, macros were sometimes used when currently constexpr variable can be used.


1 Answers

constexpr function allows the function to be evaluated at compile time, but does not require that, so your answer is "maybe". It depends on the compiler's optimization settings.

§7.1.5[dcl.constexpr]/7

A call to a constexpr function produces the same result as a call to an equivalent non-constexpr function in all respects except that a call to a constexpr function can appear in a constant expression.

If you wish to have no runtime cost, you could force compile-time evaluation by assigning it to a constexpr variable, e.g.

constexpr auto foo = CompID<Foo>();

Also note that type_info.hash_code() cannot be evaluated in compile-time (it is not a constexpr function, §18.7.1[type.info]/7). So your code is actually wrong.

like image 191
kennytm Avatar answered Oct 04 '22 21:10

kennytm