314 questions from the last 30 days
16
votes
3
answers
919
views
Necessity of `typename` for naming of local nested classes in function templates
I have a function template f, defining in its body a local class A with another nested class B. Both classes are not templates. Must I name the inner class as typename A::B or shorter variant A::B is ...
11
votes
4
answers
1k
views
C++ template dispatching not calling the correct function
The program test tag dispatching pattern, where the function process_data(tag, a, b) can accept 2 tags int_tag, float_tag. There are 3 case:
int_tag and a, b are int -> print a + b
float_tag and a,...
12
votes
8
answers
1k
views
Is it possible to expose C++ template struct (fully specialized) to C?
I want to use circular queue with different types and lengths in a project which mainly consists of C code. I'm thinking about implementing the circular queue as a C++ template struct. How to expose ...
Advice
1
vote
21
replies
329
views
Is there a reason why signed integer is used for the ssize_t?
From the man pages, I found that size_t has the range of 0 to SIZE_MAX, and ssize_t has the range of -1 to SSIZE_MAX. So, after printing those values on a 64bit system, I have the following results:
...
Advice
2
votes
4
replies
249
views
Can function-local class be defined in the global scope?
Any C++ class can be first forward declared, and defined only later in the program. Are function-local classes an exception from this rule?
Please consider a simplified program:
auto f() {
struct ...
9
votes
2
answers
698
views
Using Chrono, how can I get millisecond precision?
C++, using <chrono>, I would like to get a value formatted as <seconds>.<milliseconds>. I am using system_clock and get the current seconds as:
auto secs = duration_cast<seconds&...
6
votes
6
answers
245
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>...
18
votes
1
answer
2k
views
Whose responsibility is it to destroy a C++20 coroutine that throws from its initial suspend?
I am trying to track if a C++20 coroutine has ever suspended, so that unhandled_exception knows whether it can simply re-throw; the exception back to the caller of the initial coroutine function, or ...
2
votes
3
answers
339
views
How can I make two functions with different arguments share a function body?
I need to make a linked list implementation without using STL. push_front function has two overloads: one with const T&, the other with T&&, but the implementation is the same.
The only ...
Advice
0
votes
11
replies
205
views
Casting functions with pointer arguments to function pointers with void* argument
The following code is accepted by GCC and the resulting binary prints the expected results. But is it standard conform and would always work on different systems using different compilers?
Minimal ...
Advice
5
votes
2
replies
5k
views
Is C++26 getting destructive move semantics?
Can I express a function that consumes an object? Meaning that its destructor is not run on the moved-from object?
Like the proposed library function trivially_locate_at itself?
template <class T&...
Advice
1
vote
14
replies
250
views
Ordered array vs. hash map in c++ (100 elements)
I need help regarding a code I want to write in c++.
I want to develop a program that receives and visualizes CAN messages on a GUI. The messages in question are about 100 distinct ID's, so we're not ...
9
votes
1
answer
915
views
Is there any way to iterate data members with STL algorithms using the C++26 reflection?
With C++26 reflection, we can simply iterate all data members of an object:
#include <iostream>
#include <meta>
struct Foo {
int x;
int y;
};
void PrintFoo(const Foo& foo) {
...
3
votes
2
answers
156
views
Different output while using std::cout and std::println
In the below code I'm trying to print an unsigned char variable using std::cout and std::println. Using std::cout prints the character while std::println prints the ascii value.
Can somebody explain ...
7
votes
2
answers
731
views
Infer argument type of an overloaded function
Assuming two overloads:
void X::f(int, float);
void X::f(long, double);
is it possible, in C++17 or higher, to infer int/long (or whatever it is) from float/double for the second argument?
To be used ...
0
votes
3
answers
311
views
What are non trivial destructors in C++ used for
I am new to C++, I came from Python where there are constructors but no destructors.
What is the point of them if the memory is automatically freed when the object goes out of scope ?
Best practices
0
votes
8
replies
196
views
Should I use std::move when returning a local std::string as std::optional<std::string>?
My confusion is about the return statement inside readFileContents:
The function returns std::optional<std::string>, but the local variable is a std::string.
NRVO doesn’t apply here because ...
Best practices
3
votes
9
replies
220
views
Better key candidate, std::int16_t or std::int_fast16_t?
In a framework that makes use of the std::int* types (such as std::int16_t) as well as the std::int_fast* types (such as std::int_fast16_t) there could be general rules where one could be better than ...
Advice
0
votes
6
replies
202
views
C++ compile type endianness for use in macros
I need to layout a structure in two different ways depending on the endianness of the target platform. Currently I'm using an additional pre-compile phase to run a program to test the endianness, and ...
9
votes
1
answer
617
views
std::equal_to<void>{}(A1, B1) does not compile, while A1 == B1 compiles in C++26 for unscoped enums?
I noticed a discrepancy between C++23 and C++26 code when using googlemock:
enum A { A1, A2 };
enum B { B1, B2 };
TEST(...)
{
ASSERT_EQ(A1, B1); // compiles fine in C++23 and C++26
ASSERT_THAT(...
8
votes
1
answer
830
views
When is reinterpret_cast UB?
Does the code below contain undefined behavior (UB)?
struct A
{
int x;
char y;
};
int main()
{
std::vector<uint8_t> v(sizeof(A), 0);
A* p = reinterpret_cast<A*>(v.data());...
Advice
3
votes
7
replies
227
views
Why do people use macros to declare namespaces in c++?
Off the top of my head, I only remember LLVM's standard library do this, but I remember seeing other libraries also do this. I'm not entirely sure what is the advantage here. I feel like namespace std ...
3
votes
2
answers
277
views
Is it ok to write `&*string.end()`?
I see many places in public repositories, where the first and last iterators of std::vector/std::string/std::string_view are converted into pointers using the combination of &* operators. In ...
Advice
0
votes
13
replies
210
views
Which algorithm does the truncate function use in c++
I'm wondering how the truncate function works. C++ is just an example i'm using because it's a language I know. I've searched online and I can't seem to find how it works, simply how to use it and ...
11
votes
1
answer
654
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&...
Advice
5
votes
6
replies
181
views
How to pass arbitrary-sized array as template nontype argument?
I would like to create a template function taking an std::array<int, N> as a nontype template argument for any N (you can do that since C++20).
Explicitly I can do it like that:
#include <...
9
votes
1
answer
487
views
Why does conversion of a negated `size_t` value to `double` fail?
Consider this code:
#include <cstddef>
#include <iostream>
const double cash = 1000;
int main() {
size_t my_size_t_value = 2;
double my_double_value = -my_size_t_value*...
2
votes
3
answers
239
views
Why is a custom specialization of std::hash<std::string> allowed?
I implemented std::hash<std::string> in the usual way, by specializing the std::hash template. But then I realized that these should already be provided by the <string> header (https://www....
10
votes
3
answers
1k
views
Is creating an object not the same thing as starting its lifetime?
I've always assumed that "creating an object" is the same thing as "starting its lifetime" (and not the same thing as allocating storage for it).
But I've recently been told that &...
Advice
0
votes
7
replies
334
views
Dynamic list of type at compile time
I'm looking for a way to store type "dynamicly" in a using (or concret implementation) that would be modifable and accessible at compile-time.
I would like something like:
struct ...
Best practices
0
votes
31
replies
200
views
Does dynamic_cast violate LSP?
Does the code below violates Liskov Substitution Principle (LSP)?
class Object
{
public:
virtual ~Object() = default;
};
class A : public Object
{
public:
void print()
{
std::...
5
votes
4
answers
349
views
How to detect use of std::string SSO (short string optimization)?
If I have a long string:
std::string data("This is a string long enough so that it is not a short string");
And then I have a view onto that string:
std::string_view dataView(std::begin(...
4
votes
2
answers
161
views
Can I compare two view sentinels?
I am implementing type-erased iterators for code that uses std::views and have found a problem while trying to compare values that wrap sentinels. Basically, it seems that for some composition of ...
3
votes
2
answers
185
views
Problem with satisfying a C++ concept in a std::visit
I've a C++ concept where I need to check that the class has a particular public attribute.
My problem is that the concept works if I use it directly, but fails if I use it in std::visit.
This is the ...
Advice
0
votes
9
replies
184
views
map enum values to data types
Is it possible to map the enum values to underlaying data types to use them with std::variant?
I want to do something like the example below, but want the std::variant to understand it is an int or ...
Advice
1
vote
7
replies
179
views
How does Microsofts std::lib implementation perform debug iterator checks?
In the question Why does Microsoft's implementation of std::string require 40 bytes on the stack? the observation is made, that a std::string requires 8 additional bytes in Debug mode.
After ...
5
votes
2
answers
293
views
Why are C++ and Python giving me different answers, when given (I think) the same precision?
I have this code in C++:
#include <iostream>
#include <iomanip>
#include <limits>
#include <boost/multiprecision/mpfr.hpp>
using namespace boost::multiprecision;
template<...
Best practices
0
votes
7
replies
173
views
How to efficiently initialize a volatile struct
I would like use bit-fields to access low level memory. I'm aware of the non-portability of bitfields but they do appear to be consistently implemented on my platform (cortex-m4) on both clang and gcc....
6
votes
2
answers
185
views
If misaligned loads are supported on my platform then why does address sanitizer complain of undefined behaviour?
I'm using the Stringzilla string library, which is supposed to be close to how std::string operates. It has a flag called SZ_USE_MISALIGNED_LOADS. By default it sets it to on, and it looks like this:
/...
4
votes
2
answers
125
views
Getting a build-time unique ID for a member function within a class
I need to get a unique ID which I could use as a template argument (which means it must be statically determined at compile-time), for each member function of my class. My first idea was to use the ...
-2
votes
2
answers
250
views
Where in their documents do implementations state they won't reorder black-box functions?
Consider this example:
extern void black_box_foo();
extern void black_box_bar();
int main(){
black_box_foo(); // #1
black_box_bar(); // #2
}
#1 and #2 are functions whose definitions are ...
Advice
0
votes
6
replies
193
views
How to make a GUI library in C++
I have wanted to make a GUI library so that I can use it in my own video game that I am making and maybe in the future have it be used for other things like software. I wanted to ask where to start ...
4
votes
1
answer
263
views
Why is Eigen C++ int matrix multiplication 10x slower than float multiplication (even slower than naive n^3 algorithm) when compiled with AVX512
I'm testing int matrix multiplication, but I found that it's extremely slow everywhere (python numpy using BLAS backend is also just as slow). Int matmul being slower than float matmul is ...
5
votes
1
answer
168
views
Why does the same code, one generated by macros and the other handwritten, produces different results in MSVC?
The same code, one generated by macros and the other handwritten, produces different results.I'm lost and don't know how to fix it.
my environment is follow:
vs2019, msvc2019_64, c++14
if using ...
4
votes
2
answers
141
views
Is it possible to have a combine() function for CRC64/NVME
AWS S3 uses CRC64/NVME for its default checksum algorithm.
I need to send a trailing CRC64/NVME checksum.
The kicker is that I am middleware. There are multiple threads that are sending bytes. I ...
4
votes
2
answers
271
views
Using std::launder with reinterpret_cast?
I am probably familiar with strict aliasing rule and implicit lifetime creation in a certain degree, but I still do not understand well enough how do these terms relate to std::launder.
The following ...
0
votes
4
answers
157
views
heap-use-after-free when incorrectly assigning pointers during binary tree inversion [closed]
I was attempting the binary tree inversion question on Leetcode
https://leetcode.com/problems/invert-binary-tree/
I came up with this solution
TreeNode* invertTree(TreeNode* root) {
if (root ==...
9
votes
1
answer
257
views
Line location as default value for an argument and template argument of a function
Suppose the following foo function has a function parameter and a template parameter, both with the same default value:
template<int Line=std::source_location::current().line()>
auto foo (int ...
3
votes
1
answer
168
views
compiles when returning a non-const std::vector but fails when returning a const std::vector
In the below code, I return a std::vector<A> from the get() function. If I make the std::vector<A> be a const type, the compilation fails, otherwise it passes. Can somebody explain this ...
1
vote
2
answers
149
views
Different handling of signed value between MSVC and GCC
Take the below piece of code, that simply Trims a string, removing whitespace characters from either end:
const std::string TrimString(const std::string& s)
{
const auto iter = std::find_if(s....