Questions tagged [constexpr]

constexpr is a modifier introduced in C++11, which informs the compiler that the value of a function or variable is known or can be calculated at compile time. As such, it can be used as a constant in places where otherwise it couldn't be.

Filter by
Sorted by
Tagged with
0 votes
0 answers
36 views

How do I issue a compiler error for invalid argument to a consteval function?

I wanted to implement utility literals for evaluating roots of numbers. I implemented suffix literals that return root functions. Here's my code: #include <cmath> #include <stdexcept> ...
Samuel Okechukwu's user avatar
3 votes
1 answer
93 views

Can't use constexpr function of nested class [duplicate]

struct Foo { struct Bar { int data = 0; //constexpr Bar() = default; // Doesn't work either constexpr Bar() : data(0) {} }; static constexpr Bar bar = {}; // ...
Newline's user avatar
  • 807
0 votes
0 answers
15 views

How can I construct a class containing a vector of tuples which can be assigned to constexpr variables? [duplicate]

I was trying to construct a class, which should be constructible at compile time, containing a vector of tuples. I am using c++23. A MWE: #include <vector> #include <tuple> template<...
SRH's user avatar
  • 1
1 vote
2 answers
91 views

How to detect const char* format errors at C++ compile time?

I'm trying to write a function "my_func()" that counts the number of characters "a" in a string at compile time, which makes the code fail to compile when the count of "a"...
qingl's user avatar
  • 89
-1 votes
0 answers
78 views

How to count the number of characters in a string at compile time in C++? [duplicate]

answer This is the wrong question. Here I found the answer to my question. How to detect const char* format errors at C++ compile time? raw question I'm trying to write a function ...
qingl's user avatar
  • 89
0 votes
0 answers
38 views

Using constexpr in a class template context

In my short test program, I am trying to emulate the approach outlined in the following post: How can I use decltype to get the type of a reference? template<class T> struct unref { typedef ...
Vinod's user avatar
  • 1,041
0 votes
1 answer
84 views

Core Constant expression in the hypothetical context as stated in the definition

Reference: constexpr specifier (since C++11) constexpr variable A constexpr variable must satisfy the following requirements: ... it must have constant destruction, i.e. either: it is of class type ...
Vinod's user avatar
  • 1,041
0 votes
0 answers
14 views

What is the correlation of this accepted answer to the context of reference and constexpr?

My reference is to the following post: Why is a constexpr function on a reference not constexpr? I read through the other answers and it made sense except for the answer accepted by the creator of the ...
Vinod's user avatar
  • 1,041
-1 votes
1 answer
52 views

Can a constexpr in a derived class initialize a base class member without instantiating any of the classes?

I have some generic functionality that I want to implement only once in a base class. I have many (many!) different cases having the same structure but different data on which this functionality ...
Stefan's user avatar
  • 955
0 votes
1 answer
42 views

Passing constexpr member as a reference triggers linker error with gcc in debug or -O1 modes

The code below triggers error with gcc 'undefined reference Foo::d' and 'undefined reference Foo::i'. Strangely, it happens only if I compile it in -Og, or -O1 optimization mode, but not with -O2 or -...
one_two_three's user avatar
0 votes
1 answer
82 views

Can you dereference a shared_ptr in a constexpr function?

Im trying to pass a shared_ptr into a templated function and dereference it inside that function. Ex: constexpr bool test(std::shared_ptr<Type>&val) const { return val->some_bool; } ...
Chris's user avatar
  • 155
2 votes
2 answers
118 views

Why can functions be constexpr even if they can't ever be used in a constant expression?

The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time. The only use case for constexpr function is its ability to be resolved at ...
user10's user avatar
  • 296
0 votes
1 answer
49 views

C++ variadic template 'contains no parameter packs' when constexpr if should avoid?

I am using some c++ 20 features such as the fold operator to gain the size of a variadic template at compile time. I am then using this size in a constexpr if to avoid any usage of the variadic ...
TBCM's user avatar
  • 58
1 vote
3 answers
93 views

constexpr switch statements in C++ [duplicate]

Do we have a switch constexpr support in C++? For context, we all know that we have if constexpr for compile-time if statements. Those if-statements will have very low overhead as compiler will ...
mgNobody's user avatar
  • 738
0 votes
2 answers
59 views

Constexpr matching wide vs narrow strings types

I have a wrapper around fmt that prints to visual studio debug output. I tried to add wide string support: template <typename Arg, typename... Args> void fmt(Arg&& arg, Args&&... ...
Tom Huntington's user avatar
1 vote
1 answer
66 views

Constexpr / Compile time constant expressions bugs

I get the following error in my project upon compiling. Tried everything but unable to resolve this. Reproduced the error here: https://replit.com/join/egfoiwpgig-darshanpandhi Error error: constexpr ...
GAMERZNIGHTMARE's user avatar
0 votes
1 answer
80 views

compile time evaluated list of string literals

i am searching for a way to register some constant string information to a class, and the class holds a list of them, and the list be available at the begining of the program, so i thought the way ...
Ahmad Mansoori's user avatar
0 votes
1 answer
50 views

Is it possible to make a compile-time evaluated function return a different type than the runtime evaluation of the same function?

Is it possible, at compile time, to determine if a call to a function (a constexpr function mainly) is compile-time evaluated and than just make another version of that function (like what a template ...
Aries Victor's user avatar
0 votes
1 answer
93 views

Constexpr / compile-time constant expressions bugs

I get the following error in my project upon compiling. Tried everything but unable to resolve this. Reproduced the error here: https://replit.com/join/egfoiwpgig-darshanpandhi Error error: constexpr ...
GAMERZNIGHTMARE's user avatar
1 vote
1 answer
83 views

C++ data array initialization

I need to initialize an uint8_t array, most of it is constant (fixed identifiers), some elements encode length of next section, and some elements are variable. uint8_t data[] = { 0x01, 0x05, 0x06, ...
Tomáš Jančo's user avatar
-2 votes
2 answers
71 views

declare function arguments as constexpr [closed]

What can I do closest to passing a constexpr as a function input argument? struct X{}; template<typename T> void A<T>::foo(int i){ ... } template<> void A<X>::foo(constexpr ...
Darika Ranganathan's user avatar
3 votes
2 answers
99 views

Trying to use std::bit_cast with a bitfield struct. Why is it not constexpr?

I'm trying to get a bitmask from a bitfield struct, at compile time. One of the tricks that I tried, which looks promising to me, is using std::bit_cast, because it is supposed to be constexpr. My ...
sh-'s user avatar
  • 941
2 votes
2 answers
89 views

Detect if T is a reference member at compile time

I'm trying to detect if an argument is a reference member, at compile time. It does not catch it and I can't figure it why. #include <type_traits> struct a { a(): i1(42), i2(i1){} int i1; ...
Mariusz Witold Wisniewski's user avatar
1 vote
1 answer
72 views

Is passing an address from if constexpr block always guaranteed to be valid outside the "context"?

Given this code: #include <iostream> #include <type_traits> template <typename T> void bar(T* t_ptr=nullptr){ if constexpr(!std::is_same<T, void>()){ std::cout <...
Robin's user avatar
  • 95
1 vote
1 answer
39 views

constexpr Values with Addresses to Functions

I am attempting to have the address of a function be stored in a xor'ed form in memory similar to the XorStr function that is widely used for strings which just takes a string. Stores it in a semi-...
YoAvrageBiTz's user avatar
-1 votes
1 answer
50 views

Why is constexpr not interchangeable with const in this instance?

I have looked at some of the previous posts related to constexpr, especially this one: What's the difference between constexpr and const? My understanding based on reading on the topic is that ...
Vinod's user avatar
  • 1,041
8 votes
1 answer
120 views

Can an object with uninitialized fields be safely added in std::vector?

In the following program, default constructor of struct A does not initialize its field v. Then in a constant expression, std::vector<A> is emplaced with A() object: #include <vector> ...
Fedor's user avatar
  • 17.3k
14 votes
4 answers
880 views

Why does the address of an out-of-scope variable equal zero with constexpr?

There is something that I don't understand about constexpr semantics. Surely, the address of x allocated on the stack cannot be calculated at compile time. constexpr auto foo() { int x = 5; ...
Boris's user avatar
  • 1,313
0 votes
0 answers
82 views

constexpr function doesn't works inside constexpr if

I wanted to wrap both constexpr and non-constexpr behaviour inside a function and that seems possible (ref : calling non constexpr function from constexpr allowed in some conditions) Following shows ...
Akash's user avatar
  • 939
2 votes
1 answer
53 views

Detecting Instantiation/Calls with or without the constexpr Keyword in C++20 Constructors/Functions

I am currently trying to find a clean way to create a templated bytearray structure that can be initialized differently based on whether its constructor was instantiated with or without the constexpr ...
0xdeadbeef's user avatar
3 votes
1 answer
87 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 ...
Waker's user avatar
  • 216
1 vote
0 answers
63 views

Is there an efficient or any way to generate a template from a function parameter

I came across this code that uses a class and function parameter to decide how to handle their data in terms of templates below. class ArrayIntTypes{ public: using value_type = int; ...
Sam Moldenha's user avatar
6 votes
0 answers
119 views

Why is `constexpr vector` not allowed to allocate in `consteval` function? [duplicate]

4th Edit: the original question title is: Why constexpr specifier is not allowed for non-empty std::vector? This title, as @Barry points out, is a duplicate to C++20 constexpr vector and string not ...
Waker's user avatar
  • 216
0 votes
1 answer
49 views

How to verify an input in a constexpr function

I have a constexpr function, and I want to verify something about the input. As all is done at compile time - It seems possible for the verification be done too at compilation time: constexpr int half(...
DuduArbel's user avatar
  • 1,130
8 votes
1 answer
162 views

When can a std::initializer_list be constexpr?

According to cppreference.com, std::initializer_lists have constexpr constructors and constexpr size methods (since C++14). Although the compiler I was using seemed to agree that the size of a ...
Adrian McCarthy's user avatar
3 votes
1 answer
105 views

constexpr within method or namespace

I'm creating a constexpr array which is only used within the implementation of a method. I'm wondering what are the advantages/disadvantages of declaring this within the method vs. in the unnamed ...
Matt Stokes's user avatar
  • 4,620
0 votes
3 answers
49 views

Using a `constexpr static` function defined in a class to initialize a member of the same class

I am a little new to C++ and learning the language. Right now I'm using C++17 and G++. I'm trying to initialize an array of structs at compile time. I want to explicitly specify the array indexes in ...
Stefan's user avatar
  • 955
3 votes
1 answer
103 views

omp for loop for constexpr indexes

Suppose I have a function depending on a nontype template argument, an std::size_t, which can take value 0,...,N-1, with N known at compile time. An iteration over all values can be done with a std::...
francesco's user avatar
  • 7,254
3 votes
2 answers
94 views

Is it possible to derive template parameters from a literal integer in a formula somehow?

I have a class that wraps an integer into a range of values known only to the compiler (and the developer), the limits are unknown at runtime. The class implements operators such that the limits ...
wolfjazz's user avatar
0 votes
1 answer
153 views

When is it better to use "static constexpr" than "constexpr"?

In the answers to this question, (static constexpr vs constexpr in function body?), it is stated that static constexpr puts the variable in the .rodata section, whereas constexpr alone may allow ...
affine_scheme's user avatar
1 vote
1 answer
62 views

How to pass a enum variable to a struct with template specialization for enum

I design a struct with template specialization for enum, like this: template<DataType type> struct TypeTrait; template<> struct TypeTrait<DATA_TYPE_INT8> { static constexpr ...
Warren's user avatar
  • 11
0 votes
1 answer
84 views

Is this a compiler bug or undefined behavior?

This appears to have been fixed in more modern versions of Visual Studio, but I'm not sure if that means it was a bug or just undefined behavior. Given the following code: #include <cstdio> ...
fjjrl wlkejrlwej's user avatar
1 vote
2 answers
134 views

Is it possible to raise compile error when string is too long without macros in C++20 or lower?

I am writing a simple fixed length string struct. In runtime, if you assign strings that are too long, I will just silently truncate them. This is for embedded and the string are to be displayed on a ...
Tomáš Zato's user avatar
  • 50.3k
1 vote
0 answers
85 views

How can I achieve compile-time encryption in C++ while maintaining runtime key security?

I recently created an AES class in C++ that utilizes the constexpr feature to achieve compile-time encryption. Initially, I was excited about the idea of implementing encryption at compile time, but I'...
0xdeadbeef's user avatar
0 votes
1 answer
56 views

CLANG bug in constexpr initializer

I'm evaluating using a compile time value for the SSO maximum size to select an optimal container based on that size as well as how much heap is allocated when the size is exceeded. Works fine except ...
doug's user avatar
  • 3,858
1 vote
1 answer
91 views

Initializing static constexpr member of type std::array

I'm failing to programmatically initialize a static constexpr std::array member. This is a minimal example of my issue (for simplification size is known and small, thus initialization could be manual ...
Oersted's user avatar
  • 879
33 votes
2 answers
2k views

What are the implications of constexpr floating-point math?

Since C++11, we are able to do floating point math at compile time. C++23 and C++26 added constexpr to some functions, but not to all. constexpr floating point math is weird in general, because the ...
Jan Schultke's user avatar
  • 20.9k
2 votes
0 answers
66 views

Using objects with mutable fields inside constexpr functions

A constant expression cannot access a mutable sub-object. This is in expr.const#4.8 An object or reference is usable in constant expressions if it is ... a non-mutable subobject ... And there is a ...
Fedor's user avatar
  • 17.3k
0 votes
1 answer
65 views

write a constexpr constructor which constructs an array of another class with default constructor deleted

I have two classes A and B, where B contains an array of A. I will get a compiler error of this constructor of B (complains that the default constructor of A cannot be referenced), unless the default ...
u0804138's user avatar
1 vote
2 answers
186 views

custom minimalist std::map with constexpr operator[]

I am currently working on implementing a map container in C++, which should be able to function as a compile-time constant. More specifically, my intention is to create a static, pre-defined lookup ...
user23952's user avatar
  • 578

1
2 3 4 5
50