-
Stay up-to-date with everything C++! Content directly fetched from the subreddit just for you. Join our group for discussions : @programminginc Powered by : @r_channels
colss: a pypi module for simplifying complex mathematical expressions in numpy, built with c++, openmp, pybind11, and exprtk
https://github.com/SivaPA08/colss
https://redd.it/1t927da
@r_cpp
A small CMake helper for C++20 modules (including C++23 import std)
I’ve been experimenting with C++ modules across different compilers and build systems, and ended up writing a small CMake helper script that makes the whole thing much less painful.
It doesn’t try to reinvent module support — it relies on CMake’s native named-module features and only adds a thin layer of convenience (shorter target definitions, optional header-unit helpers, and clean presets for Clang/GCC/MSVC).
If you’re playing with modules or want a minimal, practical setup without extra tooling, you might find it useful:
👉 https://github.com/basvas-jkj/cpp\_modules
It includes example programs, compiler compatibility notes, and a summary of what actually works in practice on Windows/Linux.
If you want to see larger example, you can check my older project, fully rewritten to use C++ modules:
👉 https://github.com/basvas-jkj/oul
https://redd.it/1t8zy0v
@r_cpp
Я разработчик игровых движков. Вопросы?
Всем привет, меня зовут Роман, я учасчийся 9 класса в Алтайском крае. Начал я разрабатывать с телефона на конструкторах 3D map, pocket code и pocket game developer. Делал игры по гайдам пока летом не наткнулся на видео хауди-хо: "Изучаем питон за 1 час".
После просмотра видоса от хауди-хо я при исполнился, и решил: теперь буду разрабатывать только на питоне. Перенесëмся на пол года вперëд. 2021 год, папу отправляют на СВО, ещё через год он умирает от ранения в печень. В тоже время я началжделать свои первые фрейм ворки. 2024 год, начал делать свой первый 3д движок с интерфейсом. И вот 4 недели назад я начал делать движок на c++, lua, python и electronic.
Если кому интересновя вот сайт движка на питоне: https://exeboiulight.github.io/documentation/
А вот сайт движка на с++: https://exeboiulight.github.io/BlazeBolt-game-engine
https://redd.it/1t8b0fy
@r_cpp
I was tired of "babysitting" my AI. So I spent 6 months building a C++20 Autonomous Software House that ships while I sleep
https://github.com/chronic8000/Neon-Sovereign-AI-IDE
https://redd.it/1t7y3v7
@r_cpp
We, the C++ community, are the Borg
We, the C++ community, are the Borg. Lower your sandboxes and surrender your virtual machines. We will add your architectural and technological distinctiveness to our own. Your compiler will adapt to serve us. Resistance is futile.
Your programming language will be assimilated.
C++ is the steady, relentless workhorse of programming languages. It may adopt features gradually, but it never stops evolving, much like the tortoise that wins the race. While other languages are built around a single innovative feature—often sacrificing backward compatibility—C++ quietly observes. Developers of these new languages then face the long road of catching up to C++ in terms of features. Meanwhile, C++ users take note of promising ideas, incorporate them into C++, and render the new languages redundant.
https://redd.it/1t7du2b
@r_cpp
cvl: A C++26 library for mutating consteval state
https://github.com/friedkeenan/cvl
https://redd.it/1t75cn1
@r_cpp
std::array<std::byte, info.total_size> storage;
};
Now to finally use it:
using Struct = MetaAggregate<
Field{ type<int>, "integer_1"_name },
Field{ type<int>, "integer_2"_name },
Field{ type<std::string>, "string_1"_name },
Field{ type<std::string>, "string_2"_name }
>;
int main()
{
Struct::dump_layout();
Struct blah{ 1, 2, "3", "4" };
std::println("By name:");
std::println("blah[\"integer_1\"_field] = {}", blah["integer_1"_field]);
std::println("blah[\"integer_2\"_field] = {}", blah["integer_2"_field]);
std::println("blah[\"string_1\"_field] = {}", blah["string_1"_field]);
std::println("blah[\"string_2\"_field] = {}", blah["string_2"_field]);
blah["string_1"_field] = "foo";
std::println("By index:");
std::println("blah.get<0>() = {}", blah.get<0>());
std::println("blah.get<1>() = {}", blah.get<1>());
std::println("blah.get<2>() = {}", blah.get<2>());
std::println("blah.get<3>() = {}", blah.get<3>());
std::println("Structured bindings:");
auto [a, b, c, d] = blah.refs();
std::println("a = {}", a);
std::println("b = {}", b);
std::println("c = {}", c);
std::println("d = {}", d);
}
It's ugly, but it works.
----
### Caveats
- Since we rely on placement `new`, it cannot be made `constexpr`, sadly;
- Usage is awkward compared to real `struct`s;
- Getting all the reference categories right is tricky, I probably missed something.
I would definitely **NOT** recommend using this in production, but it was kinda fun to see whether it was possible.
https://redd.it/1t6tzvc
@r_cpp
Poor man's define_aggregate
TLDR: [Try it on Compiler Explorer](https://godbolt.org/z/sfczoP7hr).
----
While waiting for Clang to support `define_aggregate`, I got curious about whether it's possible to do something similar in C++23. Turns out it *kinda* is.
### Rules:
- Only C++23 features;
- No external programs;
- No macros;
- Generated code should be similar to just using a `struct`.
----
We start with some helper types:
#include <algorithm>
#include <array>
#include <concepts>
#include <functional>
#include <print>
#include <ranges>
#include <string_view>
#include <tuple>
#include <type_traits>
namespace detail
{
// See `type`
template <typename T>
struct FieldType
{
using Type = T;
};
// Helper for using a string as a template parameter
template <std::size_t size>
struct ConstexprStringHelper
{
std::array<char, size - 1> array;
constexpr ConstexprStringHelper(const char (&c_array)[size])
{
std::copy_n(c_array, size - 1, std::begin(array));
}
};
// See `operator""_field`
template <auto name>
struct FieldByName
{
};
We calculate the layout of our fake aggregate (sizes, alignment, offsets, ...) at compile time, like so:
// Layout information
template <auto... fields>
struct MetaAggregateInfo
{
static consteval auto calc_align(std::size_t offset, std::size_t align)
{
return (offset + align - 1) & ~(align - 1);
}
static constexpr std::array names{ std::string_view(fields.name)... };
static constexpr std::array sizes{ sizeof(typename decltype(fields)::Type)... };
static constexpr std::array aligns{ alignof(typename decltype(fields)::Type)... };
static constexpr auto max_align = std::ranges::max(aligns);
static constexpr auto offsets = [] {
std::remove_const_t<decltype(sizes)> offsets;
std::size_t next_offset = 0;
for (auto [size, align, offset] : std::views::zip(sizes, aligns, offsets))
{
offset = calc_align(next_offset, align);
next_offset = offset + size;
}
return offsets;
}();
static constexpr auto total_size = calc_align(offsets.back() + sizes.back(), max_align);
};
I found it simpler to just use a partial specialization for the case where the aggregate has no members:
template <>
struct MetaAggregateInfo<>
{
static constexpr std::array<std::string_view, 0> names{};
static constexpr std::array<std::size_t, 0> sizes{};
static constexpr std::array<std::size_t, 0> aligns{};
static constexpr auto max_align = 1uz;
static constexpr std::array<std::size_t, 0> offsets{};
static constexpr auto total_size = 1uz;
};
}
A few more helpers:
// Use to declare the type of a field. See example below.
template <typename T>
constexpr detail::FieldType<T> type;
// Type and name of a field
template <typename TheType, std::size_t size>
struct Field
{
using Type = TheType;
detail::FieldType<TheType> type;
std::array<char, size> name;
};
// Use to declare the name of a field
template <detail::ConstexprStringHelper helper>
consteval auto operator""_name()
{
return helper.array;
}
// Use with operator[] to access a field by name
template <detail::ConstexprStringHelper helper>
consteval auto operator""_field() -> detail::FieldByName<helper.array>
{
return {};
}
And now the meat of the code:
template <auto... fields>
class MetaAggregate
{
public:
static constexpr detail::MetaAggregateInfo<fields...> info{};
We define our constructors, copy/move operators and destructor. We use the offsets to get a pointer on which we can do a placement `new`. Other than that, this part is not very interesting.
MetaAggregate()
requires(std::default_initializable<typename decltype(fields)::Type> && ...)
{
std::apply(
[&](auto... offset) { (new (storage.data() + offset) decltype(fields)::Type(), ...); },
info.offsets
);
}
MetaAggregate(const MetaAggregate& other)
requires(std::copy_constructible<typename decltype(fields)::Type> && ...)
: MetaAggregate(other.refs())
{
}
MetaAggregate(MetaAggregate&& other)
requires(std::move_constructible<typename
Great to be back to C++!!!
I went to Java then Scala... then realized my code's performance sucked and C++ 17 was awesome and the portability issue is now moot.
Plus NASA's guidelines for coding where you allocate all you need upfront and never again suits me fine to not need that time consuming performance killing garbage collector.
Just to say glad to be back!
https://redd.it/1t6rmk7
@r_cpp
Created a webpage for full-text fuzzy search of all versions of the C++ standard. The result was a disaster.
https://jhcarl0814.github.io/cpp_working_drafts/cpp_working_drafts.html
https://redd.it/1t6qnow
@r_cpp
noexcept, R (P::*)(Args...) volatile>,
std::conditional_t<is_noexcept, R (P::*)(Args...) noexcept, R (P::*)(Args...)>>>;
};
template<bool is_const, bool is_volatile, bool is_noexcept, typename R, typename P, typename...Args>
using assemble_ptr_to_member_t = assemble_ptr_to_member<is_const, is_volatile, is_noexcept, R, P, Args...>::ptr;
consteval std::meta::info to_ptr_manual(std::meta::info thing) {
bool is_noexcept = std::meta::is_noexcept(thing);
bool is_const = std::meta::is_const(thing);
bool is_volatile = std::meta::is_const(thing);
auto return_t = std::meta::return_type_of(thing);
auto parameters = parameters_of(type_of(thing));
auto parent = type_of(parent_of(thing));
std::vector<std::meta::info> template_args;
if(is_const) {
template_args.push_back(std::meta::reflect_constant(true));
} else {
template_args.push_back(std::meta::reflect_constant(false));
}
if(is_volatile) {
template_args.push_back(std::meta::reflect_constant(true));
} else {
template_args.push_back(std::meta::reflect_constant(false));
}
if(is_volatile) {
template_args.push_back(std::meta::reflect_constant(true));
} else {
template_args.push_back(std::meta::reflect_constant(false));
}
template_args.push_back(return_t);
template_args.push_back(parent);
template_args.append_range(parameters);
return substitute(^^assemble_ptr_to_member_t, template_args);
}
For the curious: https://godbolt.org/z/4Gs3n4qa6
The standard could help here if either `add_pointer` got extended, or a new metafunction got invented.
https://redd.it/1t66mbc
@r_cpp
I need guide for c++ program
i am just a beginner for this thing right now i am watching
Jenny's Lectures CS IT any other suggestion for me
https://redd.it/1t63x35
@r_cpp
Are you satisfied with the current state of C++ CLI parsers?
There are already many excellent C++ CLI parsers out there, but most of them still revolve around mutable runtime builder APIs.
Most existing parsers look something like this:
CLI::App app{"example"};
std::string output;
bool verbose = false;
std::vector<std::string> inputs;
app.add_option("-o,--output", output, "output file");
app.add_flag("-v,--verbose", verbose, "verbose mode");
app.add_option("inputs", inputs, "input files")->required();
CLI11_PARSE(app, argc, argv);
Why are duplicate option names still runtime errors in C++ CLI parsers? Where is the compile-time validation?
Why is the command schema still built through runtime mutation? Many CLI schemas are effectively static. Why not treat them as a static schema and let the compiler enforce it?
One of the things I love about C++ is its ability to express intent and constraints in the type system and let the compiler enforce them.
But many C++ CLI parsers still rely heavily on runtime mutation and stringly-typed APIs.
Rust has `clap`, which is a great typed CLI parser. So what about C++?
So I wanted to explore what that direction could look like in modern C++20.
**I built a new C++ CLI parser** that takes a different approach:
#include <cli/cli.hh>
struct Args {
cli::Flag<"verbose", 'v'> verbose;
cli::StringOption<"output", 'o'> output;
cli::Positional<std::string, cli::nargs::one_or_more> inputs;
};
using namespace std;
auto main(int argc, char** argv) -> int {
// Returns parsed Args or exits with an error message.
const auto args = cli::parseOrExit<Args>(argc, argv);
std::cout << "verbose: " << args.verbose.value() << '\n';
if (args.output.has_value()) {
std::cout << "output: " << *args.output.value() << '\n';
}
for (const auto& input : args.inputs.value()) {
std::cout << input << '\n';
}
}
**Try this out on Godbolt:** [https://godbolt.org/z/53d8rEMoP](https://godbolt.org/z/53d8rEMoP)
The goal is to explore a C++20-native parser API where the command line is represented as a typed schema rather than a mutable runtime builder.
The interesting part for me is that this works in **plain C++20**, without reflection, macros, code generation, or external tooling.
Repository: [https://github.com/CLI20-dev/cli20](https://github.com/CLI20-dev/cli20)
Still early-stage. I'm mainly looking for feedback on API ergonomics, diagnostics, and the compile-time/runtime tradeoff.
https://redd.it/1t5fovs
@r_cpp
What makes a game tick? Special Issue - Buffy the Performance Slayer · Mathieu Ropert
https://mropert.github.io/2026/05/05/making_games_tick_buffy_special/
https://redd.it/1t50yp7
@r_cpp
Strategies for requiring designated initializers when constructing a type?
Given some aggregate like this:
struct InitParams {
int size = 0;
int capacity = 0;
};
And given that it is used in some factory function like this:
auto Make(InitParams ip = {}) -> std::optional<MyClass>;
I want to design the aggregate type to allow callsites like...
Make({ .size = 10, .capacity = 20 });
Make({ .size = 10 });
Make({ .capacity = 20 });
Make({});
Make();
But I also want to reject callsites like...
Make({ 10, 20 });
Make({ 10 });
Make({ 20 }); // Oops! This is the size, not the capacity!
I was hoping that reflection would unlock the ability to specify this on the type alone somehow, but I've been unable to figure out how to do it.
I can approximate this behavior using an overload set where a similar-but-different param type is accepted by a different Make overload but then that would result in default construction being ambiguous too. You can see that in action here:
struct DesignatedInitRequired {
int DONOTSPELLTHISFIELDNAME0;
int DONOTSPELLTHISFIELDNAME1;
};
auto Make(DesignatedInitRequired dir = {}) -> void = delete("Use designated init");
Make({ 10 }); // Ambiguous, ill formed (which is what I want)
Make({ 10, 20 }); // Ambiguous, ill formed (which is what I want)
Make({}); // Ambiguous, ill formed (which is NOT what I want)
Make(); // Ambiguous, ill formed (which is NOT what I want)
So I could make something to reflect on InitParams and produce DesignatedInitRequired, but that wouldn't be enough. Every function that accepts InitParams would need an overload for DesignatedInitRequired meaning that it becomes a property of the type AND its users, not just the type itself.
Any ideas on how to achieve my goal?
https://redd.it/1t4l00s
@r_cpp
fluxen: a single-header key-value store for C++20
I built fluxen to solve a problem I kept running into in my side projects. I wanted persistent key-value storage without pulling in a full database or dealing with CMake/linking.
To use fluxen, you just drop the header into your project and you have a persistent key-value database that you can learn to use in an afternoon, with no CMake, no dependencies, and no linking.
#include "fluxen.hpp"
fluxen::DB db("myapp.db");
db.put("username", "jim");
if (auto name = db.get("username")) {
std::cout << *name << "\n"; // jim
}
It supports strings, numbers, and any trivially copyable type without the need for manual serialization. Transactions batch writes into a single syscall and guarantee durability via fsync.
GitHub: [https://github.com/dvuvud/fluxen](https://github.com/dvuvud/fluxen)
Docs: [https://dvuvud.github.io/fluxen](https://dvuvud.github.io/fluxen)
https://redd.it/1t928n5
@r_cpp
When do you decide to introduce classes vs keep free functions in C++?
I’ve noticed a pattern in a lot of C++ codebases where things start out very function-oriented and straightforward, but as soon as the system grows, there’s a strong pull toward introducing classes even when the original logic doesn’t obviously need state.
At the same time, I’ve also seen the opposite problem where people avoid classes entirely and end up with large, tightly connected sets of free functions that become harder to reason about as shared data starts creeping in.
I’m trying to understand how experienced C++ developers actually decide that boundary in practice. Is it usually driven by ownership and state modeling first, or is it more about managing complexity as it appears over time?
https://redd.it/1t8b6h2
@r_cpp
I/O Multiplexing: select(), poll(), and epoll() Explaination Extended
https://0xkiire.com/io-multiplexing-guide/
https://redd.it/1t811ai
@r_cpp
Any good tech talks leveraging statement expressions?
Lambdas do a great job in a lot of cases but sometimes you need a statement expression. Any good content on youtube?
https://redd.it/1t7ual4
@r_cpp
ELF's ways to combine potentially non-unique objects – Arthur O'Dwyer
https://quuxplusone.github.io/blog/2026/05/05/potentially-nonunique-strategies/
https://redd.it/1t78gal
@r_cpp
csv-parser 5.0.0 Released: Now parsing CSVs at gigabytes per second
https://github.com/vincentlaucsb/csv-parser
https://redd.it/1t7138n
@r_cpp
decltype(fields)::Type> && ...)
: MetaAggregate(other.refs())
{
}
MetaAggregate& operator=(const MetaAggregate& other)
requires(std::copyable<typename decltype(fields)::Type> && ...)
{
std::apply(
[&](const auto&... from) {
std::apply(
[&]<typename... To>(To&&... to) { ((std::forward<To>(to) = from), ...); },
refs()
);
},
other.refs()
);
return *this;
}
MetaAggregate& operator=(MetaAggregate&& other)
requires(std::movable<typename decltype(fields)::Type> && ...)
{
std::apply(
[&](auto&&... from) {
std::apply(
[&](auto&&... to) {
((std::forward<decltype(to)>(to) = std::move(from)), ...);
},
refs()
);
},
other.refs()
);
return *this;
}
template <typename... Init>
MetaAggregate(Init&&... init)
requires(std::constructible_from<typename decltype(fields)::Type, Init> && ...)
: MetaAggregate(std::forward_as_tuple(std::forward<Init>(init)...))
{
}
template <typename... Init>
MetaAggregate(std::tuple<Init...> init_tuple)
requires(std::constructible_from<typename decltype(fields)::Type, Init> && ...)
{
std::apply(
[&](Init&&... init) {
std::apply(
[&](auto... offset) {
(new (storage.data() + offset) decltype(fields)::Type(
std::forward<Init>(init)
),
...);
},
info.offsets
);
},
std::move(init_tuple)
);
}
~MetaAggregate()
requires(std::destructible<typename decltype(fields)::Type> && ...)
{
std::apply([]<typename... T>(T&... objects) { (objects.~T(), ...); }, refs());
}
A little function to let us check that we got the layout right:
static void dump_layout(std::string_view struct_name = "MetaAggregate<...>")
{
std::array type_names = { typeid(typename decltype(fields)::Type).name()... };
std::println("Size of {}: {}", struct_name, info.total_size);
std::println("Alignment of {}: {}", struct_name, info.max_align);
std::println("Fields:");
for (auto [type_name, name, offset, size, align] :
std::views::zip(type_names, info.names, info.offsets, info.sizes, info.aligns))
{
std::println(
" - {} {} (offset: {}; size: {}; alignment: {})", type_name, name, offset, size,
align
);
}
}
Now we get to finally access the fields. First by index:
template <
std::size_t index, typename Self,
typename Type = std::tuple_element_t<index, decltype(std::tuple{ fields... })>::Type>
decltype(auto) get(this Self&& self)
{
using Ptr =
std::conditional_t<std::is_const_v<std::remove_reference_t<Self>>, const Type, Type>*;
constexpr auto offset = std::get<index>(info.offsets);
return std::forward_like<Self>(*reinterpret_cast<Ptr>(self.storage.data() + offset));
}
and finally by name. Note that we convert the name into an index at **compile time** (that's why we do all that stuff with UDLs).
template <std::size_t size, std::array<char, size> name>
static consteval std::size_t index(detail::FieldByName<name>)
{
constexpr std::array matches{ std::string_view(name) == std::string_view(fields.name)... };
constexpr auto num_matches = std::ranges::count_if(matches, std::identity{});
static_assert(num_matches > 0, "field not found");
static_assert(num_matches < 2, "multiple fields match name");
return std::distance(matches.begin(), std::ranges::find_if(matches, std::identity{}));
}
template <std::size_t size, std::array<char, size> name>
decltype(auto) operator[](this auto&& self, detail::FieldByName<name>)
{
return self.template get<index<size, name>({})>();
}
This method lets us avoid having `index_sequence`s everywhere (and also gives us some structured binding support):
template <typename Self>
auto refs(this Self&& self)
{
return [&]<std::size_t... index>(std::index_sequence<index...>) {
return std::forward_as_tuple(std::forward<Self>(self).template get<index>()...);
}(std::make_index_sequence<sizeof...(fields)>{});
}
And last but not least, our storage:
private:
alignas(info.max_align)
Poor man's defineaggregate
TLDR: [Try it on Compiler Explorer](https://godbolt.org/z/sfczoP7hr).
----
While waiting for Clang to support `defineaggregate, I got curious about whether it's possible to do something similar in C++23. Turns out it *kinda* is.struct
### Rules:
- Only C++23 features;
- No external programs;
- No macros;
- Generated code should be similar to just using a .type
----
We start with some helper types:
#include <algorithm>
#include <array>
#include <concepts>
#include <functional>
#include <print>
#include <ranges>
#include <string_view>
#include <tuple>
#include <type_traits>
namespace detail
{
// See operator""field`
template <typename T>
struct FieldType
{
using Type = T;
};
// Helper for using a string as a template parameter
template <std::size_t size>
struct ConstexprStringHelper
{
std::array<char, size - 1> array;
constexpr ConstexprStringHelper(const char (&c_array)[size])
{
std::copy_n(c_array, size - 1, std::begin(array));
}
};
// See
template <auto name>
struct FieldByName
{
};
We calculate the layout of our fake aggregate (sizes, alignment, offsets, ...) at compile time, like so:
// Layout information
template <auto... fields>
struct MetaAggregateInfo
{
static consteval auto calcalign(std::sizet offset, std::sizet align)
{
return (offset + align - 1) & ~(align - 1);
}
static constexpr std::array names{ std::stringview(fields.name)... };
static constexpr std::array sizes{ sizeof(typename decltype(fields)::Type)... };
static constexpr std::array aligns{ alignof(typename decltype(fields)::Type)... };
static constexpr auto maxalign = std::ranges::max(aligns);
static constexpr auto offsets = {
std::removeconstt<decltype(sizes)> offsets;
std::sizet nextoffset = 0;
for (auto size, align, offset : std::views::zip(sizes, aligns, offsets))
{
offset = calcalign(nextoffset, align);
nextoffset = offset + size;
}
return offsets;
}();
static constexpr auto totalsize = calcalign(offsets.back() + sizes.back(), maxalign);
};
I found it simpler to just use a partial specialization for the case where the aggregate has no members:
template <>
struct MetaAggregateInfo<>
{
static constexpr std::array<std::stringview, 0> names{};
static constexpr std::array<std::sizet, 0> sizes{};
static constexpr std::array<std::sizet, 0> aligns{};
static constexpr auto maxalign = 1uz;
static constexpr std::array<std::sizet, 0> offsets{};
static constexpr auto totalsize = 1uz;
};
}
A few more helpers:
// Use to declare the type of a field. See example below.
template <typename T>
constexpr detail::FieldType<T> type;
// Type and name of a field
template <typename TheType, std::sizet size>
struct Field
{
using Type = TheType;
detail::FieldType<TheType> type;
std::array<char, size> name;
};
// Use to declare the name of a field
template <detail::ConstexprStringHelper helper>
consteval auto operator""name()
{
return helper.array;
}
// Use with operator to access a field by name
template <detail::ConstexprStringHelper helper>
consteval auto operator""field() -> detail::FieldByName<helper.array>
{
return {};
}
And now the meat of the code:
template <auto... fields>
class MetaAggregate
{
public:
static constexpr detail::MetaAggregateInfo<fields...> info{};
We define our constructors, copy/move operators and destructor. We use the offsets to get a pointer on which we can do a placement `new`. Other than that, this part is not very interesting.
MetaAggregate()
requires(std::defaultinitializable<typename decltype(fields)::Type> && ...)
{
std::apply(
& { (new (storage.data() + offset) decltype(fields)::Type(), ...); },
info.offsets
);
}
MetaAggregate(const MetaAggregate& other)
requires(std::copyconstructible<typename decltype(fields)::Type> && ...)
: MetaAggregate(other.refs())
{
}
MetaAggregate(MetaAggregate&& other)
requires(std::moveconstructible<typename
Is it faster in C++ to use PyTorch rather then in python?
I’ve been wondering this because C++ is usually much more faster than python because it’s compiled for this apply to Ai and machine learning?
https://redd.it/1t6s9sj
@r_cpp
C++ Show and Tell - May 2026
Use this thread to share anything you've written in C++. This includes:
* a tool you've written
* a game you've been working on
* your first non-trivial C++ program
The rules of this thread are very straight forward:
* The project must involve C++ in some way.
* It must be something you (alone or with others) have done.
* Please share a link, if applicable.
* Please post images, if applicable.
If you're working on a C++ library, you can also share new releases or major updates in a dedicated post as before. The line we're drawing is between "written in C++" and "useful for C++ programmers specifically". If you're writing a C++ library or tool for C++ developers, that's something C++ programmers can use and is on-topic for a main submission. It's different if you're just using C++ to implement a generic program that isn't specifically about C++: you're free to share it here, but it wouldn't quite fit as a standalone post.
Last month's thread: https://www.reddit.com/r/cpp/comments/1salqls/c_show_and_tell_april_2026/
https://redd.it/1t6eg13
@r_cpp
C++ reflections: Getting a reflection of a type of a pointer to member, from a reflection of a member is difficult
I am going to argue that we're missing a fairly basic metafunction in C++26. While there are ways around it, none is without downsides. Let's explore!
The title is a mouthful, but I'm talking about this:
struct showcase {
void mem_fun() const {};
};
constexpr std::meta::info mem_fun_refl = ^^showcase::mem_fun;
constexpr std::meta::info mem_fun_ptr_refl = add_pointer(type_of(mem_fun_refl));
Unfortunately, that last line is just nonsense, because the type of `mem_fun` is `void() const`,
which looks similar to a free function type, with the extra cv qualifier.
`add_pointer`, whether the one in `<meta>` or in `<type_traits>` does not work there and
just produces the same type, unchanged.
Things get more confusing if `mem_fun()` does not have a cv qualifier. In that case, its type looks
just like a free function type. Now `add_pointer()` compiles and does the wrong thing.
So `add_pointer()` is not useful at all for this purpose.
One option that sometimes works is address-splicing:
constexpr std::meta::info mem_fun_refl = ^^showcase::mem_fun;
constexpr std::meta::info mem_fun_ptr_refl = ^^decltype(&[:mem_fun_refl:]);
That comes with a constraint that `mem_fun_refl` is a constant expression *in the current context*.
In other words, this approach fails when `mem_fun_refl` is an argument to a `consteval` function. I.e. the following does not compile:
consteval std::meta::info to_ptr(std::meta::info thing) {
return ^^decltype([:thing:]);
}
Okay, but we can make `std::meta::info thing` a template parameter. This is what I ended up doing in my project.
template<std::meta::info thing>
consteval std::meta::info to_ptr() {
return ^^decltype([:thing:]);
}
That works, but now whoever calls `to_ptr<thing>()` needs to also have `thing` be a constant expression in that scope. In other words, we end up with propagating "this has to be a template" up the call stack.
One last attempt: can we manually assemble a pointer to member's type? Something like
[:return_type:] ([:parent_type:]::*)([:parameter_types:]...)
[:return_type:] ([:parent_type:]::*)([:parameter_types:]...) const
[:return_type:] ([:parent_type:]::*)([:parameter_types:]...) const volatile
[:return_type:] ([:parent_type:]::*)([:parameter_types:]...) volatile
[:return_type:] ([:parent_type:]::*)([:parameter_types:]...) noexcept
[:return_type:] ([:parent_type:]::*)([:parameter_types:]...) const noexcept
[:return_type:] ([:parent_type:]::*)([:parameter_types:]...) const volatile noexcept
[:return_type:] ([:parent_type:]::*)([:parameter_types:]...) volatile noexcept
We have all of the needed info:
bool is_noexcept = std::meta::is_noexcept(thing);
bool is_const = std::meta::is_const(thing);
bool is_volatile = std::meta::is_const(thing);
auto return_t = std::meta::return_type_of(thing);
auto parameters = parameters_of(type_of(thing));
auto parent = type_of(parent_of(thing));
The trouble is now doing the manual assembly without actually splicing anything, because `thing` might not be a constant expression.
This is doable, but is quite involved:
template<bool is_const, bool is_volatile, bool is_noexcept, typename R, typename P, typename...Args>
struct assemble_ptr_to_member {
using ptr = std::condtional_t<is_const,
std::conditional_t<is_volatile,
std::conditional_t<is_noexcept, R (P::*)(Args...) const volatile noexcept, R (P::*)(Args...) const volatile>,
std::conditional_t<is_noexcept, R (P::*)(Args...) const noexcept, R (P::*)(Args...) const>,
std::conditional_t<is_volatile,
std::conditional_t<is_noexcept, R (P::*)(Args...) volatile
I rewrote part of backtrader in C++23
I rewrote core parts of backtrader in C++23 because Python backtests were getting too slow for the iteration speed I wanted.
Called it StratForge. Header-only, Apache 2.0.
https://github.com/StratCraftsAI/StratForge
Most of the work went into validation. Every indicator is checked against JSON data from backtrader. Not "close enough", it has to match.
SMA(30) on bar 247 = 1847.2361? Same here or it's a bug. I kept adding test cases until I felt like most paths were covered.
548 test cases, 40k+ assertions.
Indicators use CRTP, so no virtual calls on the hot path. About 150+ indicators (trend, momentum, volatility, volume, candlesticks, etc).
SIMD: xsimd + runtime dispatch.
Performance (512-bar dataset, P50, GCC 14, Release):
- EMA(30): 16 ns/bar
- SMA(30): 29 ns/bar
- MACD(12,26,9): 22 ns/bar
- Bollinger(20,2): 45 ns/bar
- Ichimoku(9,26,52): 67 ns/bar
Allocations aren't perfect yet. No pmr or constexpr.
Ichimoku is fully pre-reserved. The rest… still work in progress.
I like header-only. Drop it into one file and compile. Makes FetchContent easy:
FetchContent_Declare(stratforge
GIT_REPOSITORY https://github.com/StratCraftsAI/StratForge.git
GIT_TAG v0.1.0)
FetchContent_MakeAvailable(stratforge)
target_link_libraries(your_app PRIVATE stratforge)
A few occasionally useful template container classes I made, Released under the Unlicense.
Written against C++ 20 although these templates would almost definitely work on lower versions. The repository is available [here](https://git.redacted.cc/Redacted/Containers/src/branch/main). Each is in it's own header so you can just copy them out.
* Circular Array (Similar to std::queue with additional features)
* Strided Span (I think c++ 23 has something like this, Acts as a memory view in to a continuous data structure where we can skip elements while still having it presented as continuous)
* Mapped Array (unordered\_map where the actual values are located in an std::vector for good cache locality during iteration and fast lookup for any one element)
I'm definitely not best programmer ever so sorry if there's bugs lol.
https://redd.it/1t52t5w
@r_cpp
Ensinando a calcular senos em linguagem C sem bibliotecas
Olá pessoal. Este vídeo ensina a calcular senos em C usando a Série de Taylor, sem recorrer à biblioteca <math.h>.
https://youtu.be/-V3icd6VLJY
Este é um projeto de extensão da USP de São Carlos (BCC-ICMC). Agradeço quem puder responder ao formulário que está na descrição!
(Já tentaram calcular senos sem usar <math.h>?)
https://redd.it/1t4p1xi
@r_cpp
over 30 different talks and workshops from June 1st – 3rd. See the full schedule at [https://audio.dev/adc-japan-26/schedule/](https://audio.dev/adc-japan-26/schedule/)
* **ACCU On Sea Schedule Announced** – The ACCU on Sea schedule has been announced and includes over 60 sessions across the four days. Visit [https://accuonsea.uk/schedule/](https://accuonsea.uk/schedule/) for the full schedule.
* **C++Online Workshops Available** – C++Online have announced 14 workshops that will take place between the end of March and the start of June with more potentially being added if any workshops are oversubscribed. Find out more including the workshops that are available at [https://cpponline.uk/workshop-tickets-for-cpponline-2026-now-available/](https://cpponline.uk/workshop-tickets-for-cpponline-2026-now-available/)
https://redd.it/1t4h8ek
@r_cpp