61 questions
1
vote
1
answer
205
views
Making the non-trivial creation of an array constexpr
This is a follow-up of my answer to a question about initialization of arrays of non-default constructible types.
The core of the question can be summarized to this snippet, which is an over-...
6
votes
4
answers
283
views
Constexpr function that builds an integral value from a list of bits
Sometimes, it may be useful to build an integral value from a list of bits (in increasing order). Such a function could be named to_integral.
Example:
static_assert (to_integral(1,1,0,1,0,1) == ...
2
votes
1
answer
243
views
constexpr unsigned int * unsigned long not evaluated as unsigned long?
The following integer power function returns 0 when the result should be greater than 2^32 if the base argument is unsigned int, but works fine when the base argument type is changed to an unsigned ...
0
votes
1
answer
128
views
How to reconcile a constexpr function's argument being not constexpr?
A simple function like:
constexpr int f(int x) {
constexpr int y = x;
return y;
}
Seems to not be legal because x is not constexpr. This complaint is made even before I call the function, ...
4
votes
1
answer
205
views
using throw in a constexpr or a consteval function in order to generate compile-time error
The problem
Using static_assert to generate compile-time error is not always easy because it requires a constant expression as first argument. I found, on StackOverflow, several example where throw ...
3
votes
0
answers
62
views
constexpr if with function parameter error with clang, gcc is ok
Here is the test code:
#include <type_traits>
enum class ShaderType:unsigned{
Vertex = 0,
Fragment = 1,
};
template<ShaderType type> struct ShaderTypeHolder{
static constexpr ...
2
votes
2
answers
113
views
Stroustrup book constexpr example does not compile in VS C++ 2022
I am trying to reproduce constexpr example from Stroustrup book "The C++ Programming Language" 4th Ed, pp. 265-266. I am using Visual Studio 2022 Community. The code below does not compile, ...
0
votes
1
answer
299
views
Creating constexpr map filled by calls to a constexpr function in C++ 17
I have a constexpr function that calculates CRC at compile time. I need to create a map between CRCs that are generated by this function and string inputs and use them in runtime (Even better if it is ...
1
vote
3
answers
294
views
constexpr function that keeps multiplying a number until "it is big enough"
Ok, I completely messed up this question, first for the typo and second because my oversimplified minimum example didn't have any problem at all. I was considering to delete the question but seeing ...
2
votes
1
answer
294
views
How can I get a constexpr size from a std::set, which I can use to return a std::array with the number of elements in the std::set in C++23?
How can I get a constexpr size from a std::set, which I can use to return a std::array with the number of elements in the std::set in C++23 or to-be C++26, as far as supported by either G++ oder Clang?...
0
votes
1
answer
88
views
How do `constexpr` "compile time pointers" work in C++?
Background
Pointers cannot be used as T* p value parameters to a template (which is specialized at compile time), because the memory address &obj of some object T obj is only known at run time.
...
1
vote
2
answers
217
views
Using constexpr for both runtime and compile-time evaluations - passing constexpr value as a function parameter
I'm trying to make a constexpr function which will run both at compile and runtime depending on the call.The function will check a unsigned long and will return a number depending on it's value. ...
9
votes
2
answers
1k
views
Why is it possible to use the return of a lambda, passed as argument of a constexpr function argument, in a constant expression within the function?
The wording of the question title is probably incorrect and I'll fix it happily from your suggestions.
My question can be illustrated by this snippet:
#include <array>
template <typename ...
0
votes
1
answer
142
views
cout is able to run at compile-time [duplicate]
I think cout is only allowed to run at runtime but the following code proves otherwise. Or am I not understanding something deeper? I only expected it to print the message once, but it printed twice. ...
0
votes
1
answer
172
views
Where in the C++20 standard (N4860) does it say that an inline function must be defined before its use in a translation unit?
[dcl.constexpr]/1:
The constexpr specifier shall be applied only to the definition of a variable or variable template or the declaration of a function or function template. The consteval specifier ...
0
votes
1
answer
104
views
Can any reentrant function in C++ be refactored into a constexpr function?
Edit at 10/10/2023 06:30 UTC:
Thanks to valuable comments from @DrewDormann, @Solomon Slow, @Pepijn Kramer, and @user17732522, I've come to realize that I posed a question without thorough ...
3
votes
1
answer
161
views
What are the conditions that `constexpr` will start a new constant expression context?
I asked a question in Why `constexpr` specifier is not allowed for non-empty `std::vector`? previously, after finding the answer, I have another question here.
I tested and found that it is valid to ...
3
votes
1
answer
763
views
virtual and constexpr before up to C++17
I'm confused about what I read about mixing virtual and constexpr for member functions.
According to:
constexpr and virtual
Can virtual functions be constexpr?
constexpr in cppreference
up to C++17 ...
2
votes
1
answer
147
views
Different compilation results with template and non-template class having constexpr constructor
A constructor fails to quality as constexpr if the class contains std::vector as its data member since std::vector doesn't have constexpr constructor (atleast until C++17 standards, for C++20 I came ...
4
votes
0
answers
470
views
Can `constexpr` functions contain side-effects? [duplicate]
I'm working through 'Programming: Principles and Practice Using C' and need some help understanding this bit on constexpr functions on page 291:
A constexpr function behaves just like an ordinary ...
3
votes
1
answer
291
views
Why should constexpr functions contain exactly one return statement?
Reading through the constexpr specifier documentation on cppreference, I've noticed that the standard says the following:
[...] the function body [of constexpr function] must be either deleted or ...
0
votes
0
answers
81
views
how to make a field of a constexpr object constexpr too?
cube is a class that from what i know can be both constexpr and not and for some reason c.get() is not constexpr because the second cout prints 5 which mean it changed the value of c to 5 instead of c....
10
votes
1
answer
2k
views
Given C++23 relaxations on constexpr, can't constexpr be the default?
The keyword constexpr enforced pretty tight restrictions on functions on its introduction into the C++11 standard. These restrictions were loosened with C++14 and C++20 (most noteworthy):
C++14 ...
2
votes
3
answers
273
views
error while trying to compile .data() from std::array as a constexpr function in c++20
I was trying to compute an array in compilation time to speed up some functions while i encountered an error which I was unable to resolve with the help of cppreference.
The code boils down to this:
#...
1
vote
2
answers
106
views
Static assertion if one std::array is a subset of the other
I'm using two constexpr std::array:
constexpr std::array full = { 1,2,3 };
constexpr std::array subset = { 3 };
I would like to static assert if the second is a subset of the first.
In the above ...
2
votes
2
answers
160
views
What is the proper definition for a constexpr function that take a character array?
I'm writing a hashing function to help speed up string comparisons.
My codebase compares strings against a lot of const char[] constants, and it would be ideal if I could work with hashes instead. I ...
2
votes
2
answers
143
views
how to check that const array members grow monotonically at compile time
assume we have const array:
const int g_Values[] = { ... };
how check that members grow monotonically at compile time, i.e. g_Values[i] < g_Values[i + 1]
in runtime this possible to check like ...
4
votes
1
answer
335
views
Why does gcc 12.2 not optimise divisions into shifts in this constexpr function called from main()
I have been playing around with the Godbolt Compiler and typed this code:
constexpr int func(int x)
{
return x > 3 ? x * 2 : (x < -4 ? x - 4 : x / 2);
}
int main(int argc)
{
return func(...
1
vote
0
answers
46
views
Getting the value of a constexpr std::variant via constexpr function [duplicate]
This is a reduced example of a bigger function. The core issue is that at one point I try to get the value out of a constexpr std::variant via a constexpr/consteval function. This fails and I do not ...
5
votes
1
answer
924
views
Is it possible with C++20 to have a constexpr function return a tuple of types that have static constexpr array's with a value passed though a macro?
After two or three days of trying, I had to give up and wrote a "minimal" test case I hope demonstrates the problem.
What I need is a method to convert string-literals, that are passed as ...
6
votes
3
answers
408
views
A constexpr function that calculates how deep a std::vector is nested [duplicate]
Is there a way to write a constexpr function that returns how deep a std::vector is nested?
Example:
get_vector_nested_layer_count<std::vector<std::vector<int>>>() // 2
...
2
votes
0
answers
706
views
X is not a valid template argument for 'const char*' because it is not the address of a variable
I'm trying to use the resources of a temporary class object as a template parameter. But apparently this doesn't work:
godbolt
#include <iostream>
constexpr size_t size(const char* s)
{
int ...
2
votes
1
answer
167
views
Why does full `constexpr` enabling of a data structure cause the compiled code to be bigger?
At this moment of Jason Turner's 2016 CppCon talk "Practical Performance Practices", he mentions that full constexpr enabling of every data structure that can be (I'm guessing that means ...
0
votes
1
answer
259
views
Initialize a pointer with constinit
I was wondering whether I could initialize a pointer with constinit in C++20, and I didn't find any adequate answer on the internet.
I have a simple code like this:
struct a {
const char *s; // ...
0
votes
1
answer
162
views
How to check if instances of a class with a constexpr constructor get instantiated at compile time?
How can I check that instances of MyDouble will be created at compile time?
What will happen if I instantiate MyDouble with a non-constant expression?
#include <iostream>
struct MyDouble{
...
0
votes
1
answer
475
views
confusion about constexpr function body
cppreference said the following about the body of a constexpr function:
the function body must not contain:
a definition of a variable of non-literal type
a definition of a variable of static or ...
1
vote
1
answer
135
views
Implementation of typed tuple wrapper
How can an implementation look like, that wraps around e.g. a std::tuple as a static list of type/value, plus a type (not contained in tuple) to refer to some kind of owner/visitor.
I want to ...
9
votes
1
answer
1k
views
constexpr result from non-constexpr call
Recently I was surprised that the following code compiles in clang, gcc and msvc too (at least with their current versions).
struct A {
static const int value = 42;
};
constexpr int f(A a) { ...
0
votes
1
answer
209
views
literal type in constexpr expression and template parameter
Why do I can use non constexpr literal types in constexpr functions(such as reflection) and it can be returned as constexpr, but I can't use such types in template non-type parameters?
class Point {
...
3
votes
2
answers
1k
views
constexpr function which is shared in multiple modules
I noticed a strange behavior when I was working with a constexpr function.
I reduced the code to a simplified example.
Two functions are called from two different translation units (module A and B).
#...
5
votes
1
answer
892
views
A "constexpr" function should not be declared "inline"
By analyzing code using SonarLint, I got a message (the title of the question) about a destructor that is declared like below:
class Foo
{
public:
. // default ctor
. // parameterized ctor
.
...
5
votes
1
answer
1k
views
The Requirement for "Literal Type" in "constexpr" Functions
Here is my code:
class agg_t1{
int x; // private non-static data menber
};
class agg_t2{
agg_t2(){} // user-provided constructor
};
constexpr void ce1(agg_t1 arg){}; // OK
...
2
votes
1
answer
1k
views
What is the advantage of constexpr virtual functions in C++20?
I can easily say that by declaring a function as constexpr, we evaluate it during the compile-time and this saves time during run-time as the result was already produced.
On the other hand, virtual ...
4
votes
3
answers
1k
views
Compiler can't execute constexpr expression
I have code something like this:
template<typename ... Args>
constexpr size_t get_init_size(Args ... args) {
return sizeof...(Args);
}
template<typename ... Args>
constexpr auto ...
1
vote
1
answer
2k
views
Why doesn't constexpr function returning std::string doesn't compile when outside templated class? [duplicate]
Note: I am using gcc, but tested on godbolt.org and it also works on msvc, but not on clang
I accidentally discovered that the following simple function compiles while being in a templated class, but ...
1
vote
1
answer
371
views
Concatenate string literals at compile time
I need to concatenate a variable number of string literals into one to use it in static_assert()
I tried using templates with structs, but compiler does not like literals as template parameters.
error:...
1
vote
1
answer
1k
views
static compilation of an instance from json data in rust [duplicate]
I want to create a static instance at compile time (not runtime) from JSON data loaded from a file (similar to constexpr):
Example:
// a file in the project /path/to/project/data.json
{
"field1&...
4
votes
3
answers
598
views
Why constexpr method can return correctly class members whose value change during execution?
I just discovered that a constexpr method can return correctly the value of a class member that changes during execution. My question is, how is this possible if constexpr methods are supposed to be ...
0
votes
1
answer
289
views
What is preventing compile time evaluation of this constexpr function?
I'm working on a class for representing a set of hardware pins of a microcontroller (STM32). The selected pins may be discontinuous on the port, but they are assumed to be ordered. For example, if ...
1
vote
1
answer
132
views
c++ how to use constexpr value with operator []
The origin problem is I want to use const char* or char [] in template non-type arguments. Of course it is not supported now. So I want to write some code to convert char[] to std::integer_sequence. ...