2,655 questions
11
votes
1
answer
619
views
constexpr self-referencing struct
Consider the following simplified code:
template <class T> class Foo {
T t;
const T* t_ptr;
public:
constexpr Foo(T t): t(t), t_ptr(&this->t) {}
constexpr Foo(const Foo&...
Best practices
2
votes
8
replies
181
views
What is the optimal way to define a global constant string in C++20?
I need to define several constant strings that will be used across an entire C++20 project.
I am considering the following options :
constexpr char[] str1 = "foo";
constexpr std::string str2 ...
0
votes
1
answer
128
views
Is it well-formed to track POD class layouts at compile time?
I'm trying to generate compile-time info about my POD types. Getting the offset of each member has been challenging due to limitations like no pointer conversions in constexpr, but I think I've found ...
6
votes
6
answers
244
views
How to ensure order of template parameter pack with static_assert?
Let's say I have the following code:
#include <array>
#include <string>
#include <variant>
using namespace std::literals;
using known_types_t = std::variant<int, double, char>...
15
votes
1
answer
1k
views
Why can a lambda passed as an argument be used in a constant expression?
Why does this code compile?
template<typename Callable>
int foo(Callable callable)
{
static_assert(callable());
return 0;
}
static const auto r = foo([] { return true; });
Compiler ...
1
vote
2
answers
155
views
Why can't this be evaluated at compile-time?
This compiles on both Clang and GCC, but fails when I uncomment the line, and I'm wondering why since the .set() method on std::bitset is constexpr.
#include <iostream>
#include <bitset>
...
8
votes
2
answers
174
views
Calling new in a constexpr function
I am trying to write a factory function that creates a constexpr object that uses new. Is this even possible?
The following code does not compile:
aa.cpp: In function ‘int main()’: aa.cpp:23:39: in ...
8
votes
2
answers
273
views
Why should I be careful in "noexcept-ing all the functions" just like I "const all the things"?
I haven't found a video about const all the things ¹, but there's at least Con.3: By default, pass pointers and references to consts from the Cpp Core Guidelines.
There's lots of presentations and ...
3
votes
1
answer
130
views
Compilation fails when two static strings are present, but succeeds with just one
I was experimenting with constexpr std::string and I found that gcc and clang both compile this code (inspect it at compiler explorer here)
#include <string>
static constexpr std::string FIRST =...
8
votes
1
answer
155
views
Are empty structs constant expressions?
The following code compiles on all the compilers that I tested so far:
struct Alignment {
struct Center {
constexpr Center() {}
};
static const Center CENTER;
};
constexpr int foo(...
2
votes
1
answer
172
views
Compile-time manipulation of std::source_location::current()
I want to write a function that can obtain caller's function name, or at least its length, at compile time. I think obtaining std::source_location::current() is close to what I want and currently I'm ...
2
votes
2
answers
181
views
Forward string literal to consteval function
My api would require calling runtime(constFoo(str)) to get the final result, I wanted to shorten this because the real function names are kind of verbose. To do this I need to somehow wrap the ...
2
votes
3
answers
232
views
C++: How to iterate over tuple in compile-time?
How to iterate over tuple in compile-time?
problem code:
#include <array>
#include <cstddef>
#include <tuple>
namespace {
class Solution {
public:
template <size_t ...
0
votes
0
answers
121
views
Does a local constexpr variable occupy the stack space? [duplicate]
constexpr int f(int idx) {
constexpr auto arr = std::array<int, 1'000'000'000>{}; // stack overflow?
return arr[idx];
}
int main() {
return f(1024);
}
Does arr occupy the stack ...
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, ...
6
votes
1
answer
230
views
Why is std::function_ref(F*) not constexpr, while other ctors are all constexpr?
At the cppref page of std::function_ref, I found an inconsistency issue:
The copy constructor is defined as:
std::function_ref(std::function_ref const&) = default;
while the copy assignment ...
1
vote
1
answer
159
views
Sharing constants between CPU and GPU in CUDA
I'd like to share some constants between CPU and GPU in order to allow for execution of the same code (wrapped in between) on either. That includes some compile-time parameters which are most ...
5
votes
2
answers
138
views
What effect does consteval have on linkage in C++?
I have been looking at how different specifiers affect linkage but need some help understanding how consteval affects linkage.
The working draft of the standard says consteval implies inline (source):
...
6
votes
2
answers
132
views
Constant expression error when consteval function called from another
I am trying to use the return value from a consteval function UniqueSize() inside another consteval function UniqueArra to declare an array, but this results in a compiler error saying that UniqueSize(...
-2
votes
2
answers
167
views
Why can't I declare this bool constexpr even though it is evaluated at compile-time clearly?
I have no idea how the compiler decides what can be a constant and what can't. It's clear that the expression being assigned to the bool is constexpr, because it seems to have no problem returning idx ...
2
votes
1
answer
119
views
Why won't MSVC allow me to index into this array in consteval function?
This compiles on Clang and GCC, but not MSVC:
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <array>
template <uint32_t N>
struct BitfieldBits
{
...
2
votes
2
answers
152
views
Switch constexpr member initialization depending on bool template parameter
Is there a way to switch member variable initalization based on a template parameter?
Some enable_if trick or something similar?
I could do something like this with a lambda call
template<bool A>...
1
vote
1
answer
159
views
C++ builtin constexpr vs CUDA __constant__ for higher dimension array
I recently need to implement a Sobol sequence generator by CUDA.
Now to pre-store the Sobol table, I can either use a C++ native constexpr like below:
constexpr unsigned int sobol_table[NUM_DIMENSIONS]...
16
votes
3
answers
1k
views
For a member function, are constexpr, const reference return type, and const qualification mutually independent?
Using
g++ -std=gnu++17 -Werror -Wall -Wextra
the following code compiles without warning:
struct Mutable {
int x;
};
class State {
public:
constexpr const Mutable &Immutable() const {
...
1
vote
1
answer
113
views
How to generalize concept with templated function?
Given something like the following:
struct numeric_limits_max_t {
template<class T>
constexpr operator T() const noexcept {
return std::numeric_limits<T>::max();
}
};
...
14
votes
4
answers
1k
views
How can I manage perform n + m checks instead of n * m for constexpr values?
I'm building a low-latency system, in which I have functions with more than one enum value as template parameters.
Sometimes I need to resolve the enum values at runtime, but I don't want to check for ...
0
votes
1
answer
119
views
Is there any way to get `consteval`-like behavior in C++11?
I'm working on a project that must limit itself to the C++11 standard. There's one particular class I'm creating (some details below) whose most important method can, I think, often be evaluated at ...
0
votes
0
answers
127
views
Why can't this function be evaluated as a constant?
I have a situation where a function that I think should be evaluated as a constant isn't, and throws an error, however if I create local variables and use those as the argument to the function it ...
4
votes
1
answer
153
views
C23 constexpr int cannot be defined using a constexpr float or double
The following code produces an error with gcc in the latest versions:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
constexpr double d = 2.2;
constexpr int i = d*10;
...
4
votes
1
answer
216
views
How are constexpr device variables accessible from host?
My colleague came across this situation where global __device__ constexpr variables are accessible from both the host and the device.
#include <array>
#include <cstdio>
__device__ ...
8
votes
2
answers
1k
views
Compiler is out of heap when compiling recursive consteval function
I'm writing a compile-time parser PoC (compiling a literal string to std::tuple) based on C++20 (or 23 if necessary). Currently gcc, clang, and MSVC all crash for this code, and MSVC gives useful ...
2
votes
3
answers
244
views
How to declare static constexpr variable in C++?
I have a Foo class that includes an array and a static constexpr variable. As a general convention, I want to write public and private variables respectively. But, compiler error occurs 's_array_size' ...
0
votes
0
answers
88
views
Can a constexpr if statement be used as an appropriate substitute for a debug macro?
Is a debug_log written entirely as a if constexpr an appropriate (recommended) substitute for a traditional macro implementation of a debug log?
Consider the following code compiled with -O3 and -...
2
votes
1
answer
109
views
Template to check overflow and static_assert
I made some templates which are supposed to
(1) test if numbers can be added without overflow,
(2) add numbers and fail in case of overflow.
The (1) test_sum inside static_assert compiles, so I ...
6
votes
1
answer
203
views
Why is a recursive constexpr function so much faster with reference parameters than with values?
I have the following constexpr Fibonacci function:
constexpr auto fibo(unsigned int number) -> unsigned long long {
if (number < 2) return number;
return fibo(number - 1) + fibo(number - ...
1
vote
1
answer
104
views
OpenMP directive in constexpr functions
According to OpenMP specification (2.1. Directive Format)
Directives may not appear in constexpr functions or in constant expressions. Variadic parameter packs cannot be expanded into a directive or ...
0
votes
0
answers
54
views
constexpr function containing constexpr variable [duplicate]
If i have a constexpr function with a constexpr local variable its value must be known at compile time
constexpr int addSquare(int x) {
constexpr int multiplier = 2;
return x * x + multiplier;...
13
votes
0
answers
224
views
Cannot call constexpr template member function in consteval constructor
// gcc: ok
// clang: compile error
struct arg
{
consteval arg(const int i) // consteval
: i_(i)
{
chk<int>(i); // error!!
}
template <typename T>
...
5
votes
1
answer
233
views
Can initialization of static constant be skipped by 'case' label?
I have a constant declared in one case of my switch statement:
void foo( int& v ) {
switch( v ) {
case 0:
static constexpr int c{ 0 };
break;
case 1:
v = c;
...
4
votes
1
answer
231
views
Is there a standard way to keep the result of a constexpr std::string function?
C++ allows constexpr functions that return std::string. For example, using magic_enum to get a space-separated string containing all the enum values.
template <E e>
static constexpr std::string ...
4
votes
2
answers
214
views
Can I detect an integer type without listing all of them as template specializations?
I am playing around with implementing C++ std library traits. I could implement is_integral like this:
template <typename T>
is_integral
{
static constexpr bool value = false;
}
template <&...
8
votes
1
answer
252
views
Non-constexpr specialisation declaration following constexpr declaration
The C++ program below compiles with GCC trunk:
template <typename T>
struct Foo
{
constexpr void test();
};
void not_constexpr() {}
template <>
constexpr void Foo<int>::test() { }...
2
votes
1
answer
91
views
Should this example for non structural constexpr C++ argument compile?
I have the following code from Ben Deane talk.
#define CX_VALUE(...) [] { \
struct { \
constexpr auto operator()() const noexcept { return __VA_ARGS__; } \
using cx_value_tag = ...
1
vote
1
answer
450
views
How do I make a "static assertion" which is only checked on one branch of an if constexpr?
Consider the following code:
enum { a = 1, b = 2 - a};
void foo() {
if constexpr(a == 1) { }
else { static_assert(b != 1, "fail :-("); }
}
naively, one might expect the ...
3
votes
2
answers
125
views
Compile time check if string contains quotes
I want to assert that an object JsonKey if constructed with a string that is known at compile time doesn't contain a quote. Here's what I have:
LiveDemo
#include<iostream>
template <size_t N&...
9
votes
1
answer
225
views
Simple constexpr switch-case fails to compile on MSVC
If the order the case labels appears is swapped, it compiles fine (it seems to test the first branch or something even though its not called from anywhere) - Im curious about this behavior - is this a ...
2
votes
1
answer
374
views
static const vs contexpr in c23: what's the point?
c23 added the constexpr keyword to the standard, which seems to me to be quite puzzling.
I understand that the appeal would be that constexpr objects evaluate to constant expressions, whereas static ...
2
votes
0
answers
74
views
Why constructor of template struct cannot be used if it's declared inside a class? [duplicate]
I want to init a const array, so I wrote a struct:
class A {
template <int N> struct Make_0 {
long long z[N];
constexpr Make_0() : z() {
z[0] = 1;
for (int i = 1; i < N; ...
1
vote
1
answer
155
views
Mutable static variables in consteval contxt
I'm trying to implement a consteval lambda to compute the nth Fibonacci number. I want to create a result cache in the lambda which I can use if the result is already cached. Here's what I have up ...
5
votes
1
answer
136
views
How to check that a function result is constexpr even when the argument is not?
constexpr functions can yield constexpr results even when their arguments are not constexpr, if they are unused. Such is, for example, std::integral_constant::operator T:
#include <utility>
std:...