r/Cplusplus Oct 16 '25

Welcome to r/Cplusplus!

23 Upvotes

This post contains content not supported on old Reddit. Click here to view the full post


r/Cplusplus 1d ago

Tutorial Iterating through arguments in C++26 using "template for" (Python-style)

30 Upvotes

Here is how you can iterate through arguments now in C++26!:

#include <print>


template <typename ...Args>
void function(const Args& ...args)
{
    template for (const auto& arg : {args...})
    {
        using ArgT = std::decay_t<decltype(arg)>;

        if constexpr (typeid(ArgT) == typeid(double))
        {
            std::println("double: {}", arg);
        }
        else if constexpr (requires { &ArgT::toString; })
        {
            std::println("has toString: {}", arg.toString());
        }
        else
        {
            std::println("other: {}", arg);
        }
    }
}


struct MyStruct
{
    int value; // initializes with 0 in C++26
    std::string toString() const
    {
        return std::format("MyStruct value is {}", value);
    }
};


int main()
{
    function(3.14, "c-string", MyStruct{});
}

It works:

double: 3.14
other: c-string
has toString: MyStruct value is 0


...Program finished with exit code 0
Press ENTER to exit console.

template for is a new feature in C++26, and I like it very much! It's my favorite C++26 feature

It looks very pythonic at this point. 😄

Let's start with args: typename ...Args and const Args& ...args work similar to def function(*args) from python - they aggregate comma separated expressions into a variadic type or variable. {args...} also works similar to python's (*myList) - it expands a "collection" into a comma separated expressions

Then goes "template for": it's a brand new loop, which expands at compile time for each iteration. Using it, you can iterate through collections with different types inside: struct fields, tuples, list literals, and custom classes with implemented tuple protocol

Checking type of argument: this line also resembles python very much: if constexpr (typeid(ArgT) == typeid(double)). Here is the python counterpart: if type(arg) is bool. There are more ways to do this check, but I think this one looks the most direct. Although you can want to use not exactly "double" type, but a convertible to it, or any floating point number type. There are standard concepts for these cases: std::convertible_to, and std::floating_point

Checking for a member: here I used an anonymous concept: if constexpr ( requires { ...;} ). Inside this concept we should put an expression that we are testing. it's a sort of python's hasattr(arg, 'toString'), but more powerful and more fragile at the same time. The expression here is taking a member reference to "toString": &ArgT::toString;. It's a better approach than testing arg.toString(), because it won't fail if "toString" isn't a constant method, or has more than 0 arguments. But it's still far from ideal, because if the object has multiply overloaded "toString" methods (what's actually a pretty realistic scenario), it will fail, and the error message will be misleading. In this case the error will be that formatter is not implemented for the "other" branch, however the actual error is in "has toString" branch. So, don't use anonymous concepts in real project, use full fledged concepts in pair with static_asserts

It's fascinating! This is still a templates metaprogramming in C++, but it looks much-much more clean than infamous std::enable_if


r/Cplusplus 16h ago

Question С-плюсеры, общий сбор

Thumbnail
0 Upvotes

r/Cplusplus 2d ago

Feedback For anyone who is interested in https://www.oreilly.com/library/view/sfml-game-development/9781785287343

Thumbnail
0 Upvotes

r/Cplusplus 2d ago

Discussion I am trying to build AgentMesh: C++20 runtime for executing agent/task DAGs

0 Upvotes

I've been building an open-source C++20 runtime called AgentMesh for executing multi-agent/task DAGs.

The goal is to keep high-level application code in Python while moving execution-critical infrastructure into native C++.

Current areas include:

  • DAG scheduling
  • concurrency
  • task/agent communication
  • state management
  • crash recovery
  • Pybind11 integration

I'm particularly interested in the engineering trade-offs around the Python/C++ boundary and how much work should actually live inside the native runtime.

The next major milestone is distributed execution over gRPC.

GitHub:

https://github.com/DevrG03/AgentMesh

Documentation:

https://github.com/DevrG03/AgentMesh/wiki

I'd appreciate code/architecture feedback from C++ developers.


r/Cplusplus 5d ago

Feedback From 3 seconds to 600ms — building a virtual package system for my WASM multiplayer game

Post image
22 Upvotes

Hi there, I'm building a multiplayer game in C++/WASM link. While testing with friends, I noticed the game took ~3s to load — 5s on slower connections. Instead of accepting it, I built my own virtual package system in C++ and cut the load time from 3s to ~600ms.

Here's the source: nodepp-filepack


Compression (packing assets):

```cpp

define NODEPP_ALLOW_THROW_EXCEPTION 0

include <nodepp/nodepp.h>

include <nodepp/zlib.h>

include <nodepp/fs.h>

include <filepack/filepack.h>

using namespace nodepp;

void onMain() {

filepack_t pack("skeld.npk");
auto x = ptr_t<ulong>(0UL, 0UL);

fs::read_folder("./assets")
.fail([](except_t err) { console::log(">>", err); })
.then([=](ptr_t<string_t> list) {
    pack.iterate_writable_stream( list, [=](string_t name, file_t stream_o ) {
        pack.get_readable_info(name).value()["compressed"] = true;
        zlib::gzip::pipe(file_t(list[x[0]], "r"), stream_o);
        x[0]++;
    });
});

} ```


Decompression (loading assets):

```cpp

define NODEPP_ALLOW_THROW_EXCEPTION 0

include <nodepp/nodepp.h>

include <nodepp/zlib.h>

include <nodepp/fs.h>

include <filepack/filepack.h>

using namespace nodepp;

void onMain() { filepack_t pack("skeld.npk"); auto stream = pack.get_readable_stream("map.png").value();

zlib::gunzip::pipe(stream, file_t("map.png", "w"));

} ```


How it works:

  • All assets are packed into a single .npk file with optional compression.
  • Assets are streamed and decompressed on the fly — nothing is loaded into memory all at once.
  • The result: faster loading, lower memory usage, and a better experience for players on slow connections.

Nodepp is open source: github.com/NodeppOfficial/nodepp


r/Cplusplus 7d ago

Question what would you say to someone that is struggling to implement linked lists in c++ even though they understand the basic concept of the data structure itself (i think my problem is with the syntax )

18 Upvotes

what would you say to someone that is struggling to implement linked lists in c++ even though they understand the basic concept of the data structure itself (i think my problem is with the syntax )


r/Cplusplus 6d ago

Discussion How I finally understood C++ Copy, References and Move Semantics (Real-world analogies)

Thumbnail
3 Upvotes

r/Cplusplus 6d ago

Question Urgent help needed!!

Thumbnail
0 Upvotes

r/Cplusplus 9d ago

Question Resources to learn C++ and DSA for Competitive Programming (and in general)

58 Upvotes

Hello everyone, I am a SWE student from India. I wanna learn C++ for competitive programming and DSA, jobs, building projects, etc as well. My reasons:

- Not only learning it for jobs, but because, C++ is very fast and has the capability of efficiently interacting with both the high level and low level systems. These are the reasons which make me learn it, especially as I am interested in how memory, RAM, GPU and other things work in the computer.

- For the sake of computer science and programming. I am interested in learning the core cs fundamentals and concepts to make myself a better software/cs engineer - to solve problems, code solutions, etc.

- I am interested in ICPC, DSA and competitive programming as well. So that would make me learn it anyways.

Honestly, I have asked and read about this question many times but I haven't got a clear and one-stop answer yet. These are the things that ppl/ai chatbots suggest me and what I read (also my reasons for not using them yet):

- USACO guide (too big)
- learncpp (good but too vast)
- the cherno's yt channel (some say they dont cover concepts in depth)
- books (too lengthy as well)

I am not looking for shortcuts, nor am I avoiding these resources because they are too big. I am ready to invest my heart and soul into learning things. But, being an engineering student, I have many other different subjects to study as well for the college. I am so much interested into AI/ML and Web dev as well.

For context, these are the things I know (i.e. I'm not starting programming from absolute 0) :

- HTML/CSS and basic JS (learning from The Odin Project but paused rn)
- basic C (learned from college and CS50x)
- Python (learned from CS50 Python course)
- SQL (learning at college + by myself)
- Java (learning at college + by myself)

The college has made the latter two subjects and C++/DSA compulsory for this year. But, I don't wanna invest that much time into studying those 2 deeply (I mean Java and SQL). I am focusing on C++/DSA, Web Dev and AI/ML as of now.

So, given my all the background and interests, could you guys please suggest me different resources to learn C++ and DSA? Also, for learning things about Competitive Programming and improving myself there.

My goal for now is to speedrun the basics of C++ (because I have already learned the basics of programming and C earlier) + learn concepts of DSA in detailed manner -> then proceed with competitive programming -> then participate in contests and along the way learn different concepts of C++ and DSA.

How is my approach? If there's any other better one, please do suggest me. Thank you!


r/Cplusplus 8d ago

Feedback Raw wayland/vulkan boilerplate library, no SwapchainKHR, modern explicit sync (syncobject, drm)

Thumbnail
3 Upvotes

r/Cplusplus 8d ago

Question Beginner looking for advice on what to learn next in C++

Thumbnail
4 Upvotes

r/Cplusplus 9d ago

Tutorial C++26 Contracts: What Do They Add Beyond Manual Checks and Assertions?

Thumbnail
techfortalk.co.uk
6 Upvotes

r/Cplusplus 10d ago

Discussion Implementing arbitary-precision square rooting algorithm using the long division in C++ (with custom BigNumber library)

13 Upvotes

Hello everyone,

Some days ago, I have finished building an algorithm in C++ using only my mobile phone (Termux and Helix), and I want to show it to you!

So, it uses the long division method. Why not the Newton-Rasolph method or use the GMP library? Because this program was built for two reasons:

  1. An educational purpose of learning how to build an algorithm I have an idea of and optimize it as much as I can.

  2. To learn how to implement a mathematical algorithm as a program, and to also learn more about C++.

The performance of this algorithm is following the O(n²), but with a small constant, since I have optimized this algorithm as much as I can. You can see the benchmark in the GitHub link down below. Here is how I optimized it:

This algorithm has a custom BigNumber class that makes a number as a vector, each digit is represented as an element in the vector, and, each digit follows a base 1017 number instead of a decimal digit! This is the underlying logic behind very famous libraries like BigInt, but since these libraries are so general (they have to deal with very large multiplications, division, negatives and many general cases). This class recognized that the max number is being multiplied to the number is 100 (see the long division method) and implemented base 1017. Therefore, since 100<1017 (the base), then the multiplication is just multiplying one digit by the number. You can check the code for more

The way the algorithm predicts the digit is the binary search, it checks a number, and then eliminates half of the domain of search. This way, it is faster by 50-60% than the ordinary linear search.

And more! You can check the README of the project in this repo:

https://github.com/hasan-mazen-darwish/algorithm-square-rooter

I spent more time on this REAMDE than the actual code, so I hope you don't get lost 😅

I'm open for any discussion or any question! Feel free to ask anything or criticize this project or a specific line of code!


r/Cplusplus 10d ago

Question Please help

0 Upvotes

Im a newbie btw and i need some help fixing this without giving my soul to an AI company


r/Cplusplus 12d ago

News Speak at code::dive 2026 📣

Post image
1 Upvotes

r/Cplusplus 13d ago

Feedback Low latency c++

63 Upvotes

I want to learn the ins and outs of low latency c++, so far I have read tour of c++, started reading concurrency in c++ (about 3 chaps done) and done a lot of competitive programming (is this irrelevant?). In your experience, is this the right way of approaching the subject? Is there a different better way? Any advise is much appreciated.


r/Cplusplus 13d ago

Question What are the use for C++??

0 Upvotes

กำลังคิดจะเรียนภาษา C++ อยู่ อยากรู้ว่ามันทำอะไรได้บ้าง ช่วยให้คำแนะนำหน่อยได้ไหม?


r/Cplusplus 15d ago

Question Can someone pls explain me whats actually going on here?

31 Upvotes

This code was in my university slides, is it worth understanding all of this?
It was referring to something like "reference is const pointer", I dont really get this.


r/Cplusplus 16d ago

Question Is it possible to check if a method exists, and if not, create a fallback one?

23 Upvotes

I have a namespace with methods with which I would like to have an implicit fallback to a different method if the aforementioned method doesn't exist. As an example, here's how I made my states.

#pragma once
#include "godot_cpp/classes/character_body2d.hpp"
#include "statemachine/base/state_base.h"

namespace GameLogic::States::ColorState
{
    constexpr double MAX_TIMER { 3.0 };
    struct ColorStateData
    {
        STATESTRUCT();
        godot::Ref<godot::StateMachine> state_machine;
        CharacterBody2D* entity;
        double timer {0.0};
    };
    void setup_state(ColorStateData& data);
    void enter_state(ColorStateData& data);
    void physics_update_state(ColorStateData& data, double delta);
    void update_state(ColorStateData& data, double delta);
    void exit_state(ColorStateData& data);
    STATESPACE(ColorStateData, GameLogic::States::ColorState)
}

It would be nice if I didn't have to specify 5 methods each time. Can I build this check into STATESPACE? In C++ 17 by the way.


r/Cplusplus 16d ago

Tutorial C++26 Reflection Annotations: Automated Member Validation

Thumbnail
techfortalk.co.uk
6 Upvotes

r/Cplusplus 16d ago

Question Making a table maker

2 Upvotes

I have a background in MS Access VBA, I’m very new to C++. This may be way beyond my current ability to understand, but if I wanted to write a function that generated data tables in C++ how would I approach this?

For context, I’m making a text-based RPG design engine project for fun. I would like to make an app that creates data tables to store level design, character sheet info, etc. for the designer to dynamically make character types and maps


r/Cplusplus 17d ago

Question Best resource to learn c++ to build projects

53 Upvotes

Guys... I know c++ only at a basic level. I need to learn

c++ enought to build projects (of course using supporting technologies). Can some one recommended any book/website/yt course??


r/Cplusplus 21d ago

Discussion 27 years of building a C++ code generator

37 Upvotes

I'm celebrating another year of building a code generator that helps build distributed systems.  It's implemented as a 3-tier system. The back and middle tiers only run on Linux. The front tier is portable.  My goal is to bring software services and code generation together in one platform.

I've made some progress but there's still a long way to go. I welcome suggestions on how to improve the software and documentation. Stars on my repo are also appreciated. And I'm willing to spend 16 hours/week for six months on a project if we use my software as part of the project.

Thanks in advance,

Middlewarian


r/Cplusplus 21d ago

News Rewrite TanjaOS in C++?

Post image
0 Upvotes