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.
2,181
questions
2
votes
1
answer
49
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
56
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; // ...
5
votes
2
answers
43
views
Why does a non-constexpr std::integral_constant work as a template argument?
My question is why the following code is valid C++:
#include <iostream>
#include <tuple>
#include <type_traits>
std::tuple<const char *, const char *> tuple("Hello", ...
2
votes
1
answer
50
views
Generating compile time functions string for formatting strings with libfmt
I want to create a nice table in stdout. The table has a lot of headers that are mainly compiletime strings. For example:
std::cout << fmt::format("|{0:-^80}|\n", "File ...
0
votes
1
answer
66
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
0
answers
46
views
Parsing Function Calls with `constexpr` library in C++
I'm at the end of the semester and need to get this in, I have been struggling for the last few days to implement function calls into my language. I am using the ctpg library which implements a ...
0
votes
0
answers
50
views
C++17: std::is_same_v fails unexpectedly
Can someone explain to me, why this code fails to compile
friend
std::ostream& operator<<(std::ostream& os, const Matrix<T> &matrix) {
os << matrix.rows();
os <...
1
vote
2
answers
72
views
How can I enable a constexpr `missing return statement` active error without warnings?
Suppose I have constexpr data set. I mostly use it at compile time, it stores data for settings that can affect future constexpr statements. The string_view allows me to name these settings and search ...
0
votes
1
answer
96
views
c++ constexpr concatenate char*
Context:
In my company we generate a lot of types based on IDL files. Some of the types require special logic so they are handcoded but follow the same pattern as the generated ones. We have a ...
3
votes
1
answer
103
views
Do compilers `constexpr` everything?
Do compilers try to constexpr1 everything? Not just functions/variables/things explicitly marked constexpr by the programmer? Before someone comments
yeah duh, that's what optimization is
A better ...
1
vote
1
answer
64
views
Does constexpr really imply const? [duplicate]
Compare the following:
I have a static member in a class that is either const constexpr or just constexpr. According to this explanation on MS Docs constexpr implies constness:
All constexpr ...
5
votes
2
answers
74
views
How to call a templated function for each type in a tuple (acting as type list) with tuple b as argument
How to call a template function for each type in a typelist with arguments (e.g. another tuple)?
Given is a typelist std::tuple<T1, T2, T3, ...> and a std::tuple containing data.
template <...
0
votes
0
answers
33
views
Checking for == comparison (constexpr) operator in C++ with MSVC [duplicate]
I'm attempting to check if a type generally implements the comparison == operator. More specifically I need to know if it returns an 'int' but I'm not attempting to go that far, yet. Just the ...
0
votes
1
answer
46
views
Declare a constexpr static member that is a function of a potentially-absent member in a template parameter?
I have a templated class for which I would like to provide a constexpr integer whose value is determined by the presence or absence of a constexpr integer in the template parameter:
template<...
0
votes
1
answer
91
views
How can I incrementally create an array of types?
template<typename ...Args>
class TypesArray {
std::tuple<Args...> *tuple_;
template<typename T>
struct push_back_s {
using type = TypesArray<Args..., T>;
...
19
votes
4
answers
1k
views
How to extract all tuple elements of given type(s) into new tuple
The existing tuple overloads of std::get are limited to return exactly 1 element by index, or type. Imagine having a tuple with multiple elements of the same type and you want to extract all of them ...
0
votes
1
answer
47
views
How to group data in tuples of tuples into a tuple of vectors
I want to group data of tuples in tuples into a tuple of vectors.
Given is a tuple of tuples containing data. There are multiple duplicate types, that's data should be grouped into a vector of each ...
0
votes
1
answer
97
views
Is this pointer always a runtime construct
I am learning about the this pointer in C++. And i came across the following statement from the standard:
An expression e is a core constant expression unless the evaluation of e, following the rules ...
0
votes
0
answers
53
views
static constexpr, static const, constexpr, const, constinit?
If I need to reference the size of two 4x4 float matrices, which is 128, across multiple functions and stuff, what is the best way to do it that doesn't use macros. I know that for something trivial ...
1
vote
2
answers
100
views
Why constexpr std::string_view yields "format not a string literal" warning?
The following use of constexpr std::string_view produces "format not a string literal" warning:
constexpr std::string_view string_view_format_str = "hello %s";
snprintf(...
0
votes
1
answer
14
views
Mutually dependent constexpr constructors
I have two classes, each constructible from the other.
Example:
class B;
class A{
public:
double val;
constexpr A(B b): val(b.val){};
};
class B{
public:
double val;
constexpr B(A a): val(...
3
votes
1
answer
73
views
How to invoke a templated static class method having tuple input in a constexpr way
How can a static constexpr class::method (int i1, int i2, int i3) be invoked, having input data available as tuple<int, int, int> in a constexpr way.
The default approach is using std::apply to ...
3
votes
0
answers
46
views
Constant evaluation of self-assignment in member initialization
In the following program, constexpr function foo() makes an object of A with the field x=1, then constructs another object on top of it using std::construct_at and default initialization x=x, then the ...
1
vote
1
answer
45
views
Why aren't constexpr const scoped variables implicitly static?
(Following to this question:)
void foo() {
constexpr const auto my_lambda = [](int z) { return z+1; };
}
Apparently, my_lambda is "not static". In what sense is it not-static, other ...
5
votes
0
answers
67
views
C++ - assigning constexpr char * to static char * copies the string ... is it a bug?
Consider the following program. It simply copies a constexpr const char * to a static const char *. I would expect the pointer to be copied, and be identical. And this is what happens with gcc, clang, ...
1
vote
0
answers
35
views
`if constexpr` with `template` arguments vs. with `constexpr` expressions [duplicate]
Consider the following definition:
template<int n> struct Foo;
template<> struct Foo<1> { void fn1(); };
template<> struct Foo<2> { void fn2(); };
Foo<1> has a ...
1
vote
1
answer
79
views
How to check a type has constexpr constructor
I want my class use another implementation for types don't have constexpr constructor.
like this:
template <typename A>
class foo
{
public:
// if A has constexpr constructor
constexpr ...
2
votes
1
answer
89
views
Using constexpr and string_view in module
Modern C++ offers constexpr and std::string_view as a convenient alternative to string literals. However, I am unable to link to a "constexpr std::string_view" within a module. By contrast, ...
0
votes
1
answer
79
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 ...
0
votes
1
answer
53
views
Provide constexpr-safe simplified exception message when consteval'd, otherwise stringstream verbose info
Imagine this simple constexpr function:
// Whatever, the exact values don't matter for this example
constexpr float items[100] = { 1.23f, 4.56f };
constexpr int length = 12;
constexpr float getItem(...
0
votes
0
answers
45
views
constexpr Functions that throw (runtime) errors
I'm trying to write a function that I would like to be used in both constexpr situations as well as runtime situations. The function does several debug-only checks, and these calls are causing the ...
-1
votes
1
answer
50
views
Multi-Dimensional Array declaration with constexpr free function v.s. method
I have this issue:
This code works fine for me:
constexpr int pow(int first, int second)
{
int out = 1;
for (int i = 0; i < second; i++)
out *= first;
return out;
}
template<...
0
votes
0
answers
25
views
How to make constexpr if expression work with string_view passed by parameter [duplicate]
How to pass string parameter to template function to be able to use constexpr if inside?
#include <string_view>
#include <iostream>
using namespace std::literals;
template<typename T&...
-1
votes
1
answer
63
views
How to enumerate a constant array at compile time in C++?
I am trying to generate a hash at COMPILE TIME from a literal string (array of characters). For example:
unsigned long long compiledHash = ComputeHash("literal string");
I am currently ...
0
votes
1
answer
60
views
static constexpr chrono as struct member
I have an interface header with a struct like looks like this (C++11):
// header
struct MyStruct
{
std::chrono::milliseconds time_1{defaultTime};
std::chrono::milliseconds time_2{defaultTime};
...
0
votes
3
answers
84
views
Definition of static data member without repeating its type
When I have a class with a static const or constexpr data member, defining that variable reqires me to repeat stuff:
/// my_class.hpp
class my_class { constexpr static int x = 1; };
/// my_class.cpp
#...
0
votes
1
answer
109
views
inline static constexpr vs global inline constexpr
Suppose that I have a few inline constexpr variables (named as default_y and default_x) in a header file and I decided to move them to a class that they are completely related to and mark them static (...
1
vote
0
answers
56
views
if constexpr behavior differs between C++17 and C++20 [duplicate]
I am seeing some unexpected compile-time behavior when compiling a piece of code using MSVC 17.1.3 in C++20 standard compliance mode.
#include <type_traits>
#include <stdexcept>
template &...
0
votes
2
answers
53
views
Captured in-line array in constexpr variable gets lost on runtime
I'm trying to create an [int/enum]-to-text mapping class with as little overhead as possible for it's users. It's constructor should be passed a list of value-to-text mappings, which can be queried ...
0
votes
2
answers
74
views
Why isn't constexpr guaranteed to run during compilation?
Why isn't constexpr guaranteed to run during compilation?
Additionally, why was consteval added instead of changing constexpr to guarantee a compile-time execution?
1
vote
0
answers
53
views
Constant calculation of bit-band address in C++
I have following class:
class Bit
{
void * bb_addr;
public:
constexpr Bit ( void * __data, int bitpos )
: bb_addr((void*)(0x22000000 + ((uint32_t)(__data) - 0x20000000) * ...
2
votes
1
answer
97
views
Why does `consteval` not behave as expected?
inline consteval unsigned char operator""_UC(const unsigned long long n)
{
return static_cast<unsigned char>(n);
}
inline consteval char f1(auto const octet)
{
return char(...
4
votes
3
answers
163
views
changing active constexpr union member using construct_at
I'm trying to change the active member of a constexpr union using construct_at and get the following error when constructor initializes it's member using initializer list vs. member. Can someone ...
0
votes
0
answers
28
views
in C++ can I define a constant pointer for GMP?
This seems like it should be simple but it doesn't seem to be. I know I can define a constant by using
#define magicNumber 20
But in my class I need to multiply and divide by 2 large numbers over ...
4
votes
1
answer
98
views
How to emulate std::is_constant_evaluated in c++17?
I've got the following code doing what I want in c++20:
#include <iostream>
struct IntContainer
{
int value;
constexpr IntContainer(int init):value(init)
{
if(std::...
6
votes
1
answer
131
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
51
views
Constexpr expand constructor parameter pack into member array (C++11)
I want to expand a pack of variadic parameters into a struct member in C++11. My approach is the following:
template <typename... Ts>
struct cxpr_struct
{
constexpr cxpr_struct(Ts... Args) : ...
0
votes
1
answer
36
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 {
...
0
votes
1
answer
49
views
Constructing a constexpr lambda with member function pointer
I am attempting to build a constexpr lambda that uses a member function pointer as part some type of registration process.
The problem is the outermost function that is part of that process is not ...
1
vote
1
answer
90
views
C++20 Module with Namespace
I am hoping to receive some input on an issue I encountered while attempting to learn c++20 modules.
In short, I would like a namespace containing const and/or constexpr variables to be implemented ...