Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce compile-time constexpr [duplicate]

In C++11 we get constexpr:

constexpr int foo (int x) {
    return x + 1;
}

Is it possible to make invocations of foo with a dynamic value of x a compile time error? That is, I want to create a foo such that one can only pass in constexpr arguments.

like image 315
Thomas Eding Avatar asked Jul 15 '13 20:07

Thomas Eding


People also ask

Is constexpr guaranteed to be compile time?

A constexpr function that is eligible to be evaluated at compile-time will only be evaluated at compile-time if the return value is used where a constant expression is required. Otherwise, compile-time evaluation is not guaranteed.

Does constexpr improve performance?

Understanding constexpr Specifier in C++ constexpr is a feature added in C++ 11. The main idea is a performance improvement of programs by doing computations at compile time rather than run time. Note that once a program is compiled and finalized by the developer, it is run multiple times by users.

Is constexpr constant?

The keyword constexpr was introduced in C++11 and improved in C++14. It means constant expression.

When to use #define vs constexpr?

#define (also called a 'macro') is simply a text substitution that happens during preprocessor phase, before the actual compiler. And it is obviously not typed. constexpr on the other hand, happens during actual parsing. And it is indeed typed.


1 Answers

Yes, it can now be done in purely idiomatic C++, since C++20 added support for this kind of problem. You annotate a function with consteval and can be sure that it's being evaluated during compile time. https://en.cppreference.com/w/cpp/language/consteval

consteval int foo( int x ) {
    return x + 1;
}

int main( int argc, char *argv[] )
{
    return foo( argc ); // This will not compile
    return foo( 1 );    // This works
}

Also see this godbolt.org demo in the 3 most relevant compilers.

like image 97
JanSordid Avatar answered Oct 18 '22 17:10

JanSordid