r_cpp | Unsorted

Telegram-канал r_cpp - C++ - Reddit

-

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

Subscribe to a channel

C++ - Reddit

Pure Virtual C++ 2025: MSVC C++23 Conformance
https://www.youtube.com/watch?v=MfYZQu9zG80

https://redd.it/1k3ib0j
@r_cpp

Читать полностью…

C++ - Reddit

Reasons to use the system allocator instead of a library (jemalloc, tcmalloc, etc...) ?

Hi folks, I'm curious if there are reasons to continue to use the system (glibc) allocator instead of one of the modern high-performance allocators like jemalloc, tcmalloc, mimalloc, etc. Especially in the context of a multi-threaded program.

I'm not interested in answers like "my program is single threaded" or "never tried em, didn't need em", "default allocator seems fine".

I'm more interested in answers like "we tried Xmalloc and experienced a performance regression under Y scenario", or "Xmalloc caused conflicts when building with Y library".

Context: I'm nearing the first major release of my C++20 coroutine runtime / tasking library and one thing I noticed is that many of the competitors (TBB, libfork, boost::cobalt) ship some kind of custom allocator behavior. This is because coroutines in the current state nearly always allocate, and thus allocation can become a huge bottleneck in the program when using the default allocator. This is especially true in a multithreaded program - glibc malloc performs VERY poorly when doing fork-join work stealing.

However, I observed that if I simply link all of the benchmarks to tcmalloc, the performance gap nearly disappears. It seems to me that if you're using a multithreaded program with coroutines, then you will also have other sources of multithreaded allocations (for data being returned from I/O), so it would behoove you to link your program to tcmalloc anyway.

I frankly have no desire to implement a custom allocator, and any attempts to do so have been slower than the default when just using tcmalloc. I already have to implement multiple queues, lockfree data structures, all the coroutine machinery, awaitable customizations, executors, etc.... but implementing an allocator is another giant rabbit hole. Given that allocator design is an area of active research, it seems like hubris to assume I can even produce something performant in this area. It seems far more reasonable to let the allocator experts build the allocator, and focus on delivering the core competency of the library.

So far, my recommendation is to simply replace your system allocator (it's very easy to add -ltcmalloc). But I'm wondering if this is a showstopper for some people? Is there something blocking you from replacing global malloc?

https://redd.it/1k30fcd
@r_cpp

Читать полностью…

C++ - Reddit

Come here if you need a project to get started in C++!

Hi,

Every once in a while we have posts of people asking how to get into C++, or ideas of projects they could contribute to. I'd like to try and propose something for these people.

I work on an open source game written in C++ and targeting Android devices. The game is playable but incomplete, and there is always more work to be done, and stuff that would be great but won't be a priority before long. What I propose is to provide some kind of mentoring for anyone who would want to try software development on my project.

The project: Bim! is a 2D last-man-standing arcade online game. It is in a playable state and not available in the stores yet. You can get the APK from the releases page if you want to try it out. You can do gameplay, server, client, UI, tooling... The technology stack contains Axmol, EnTT, CMake, GoogleTest, Boost, to name the most known. This is free software: AGPL 3 and CC-BY-SA. Development is done in a Linux environment.

What you get: concrete work with meaningful goals; experience in non-toy projects; feedback from a random developer with I-don't-count-anymore years of programming behind him. I used to write code reviews for fun for a couple of public projects (e.g. toml++, stevensStringLib, among others). This is the kind of feedback you could get. Bonus: you'll bring joy in the life of people who play the game ;)

Note that this is a pet project for me, so the main goal is to have fun working on it :) The exchanges will happen during my free time.

What I get: "free" workforce for my project, a way to have progress on the tasks on which I can't work, and an opportunity to become a better mentor.

I've written a couple of tasks to work on. If you're interested, pick one, and let's start a discussion!

- Use bim::table_2d in bim::arena
- Game feature: invisibility
- Enable LTO in Android release builds
- Display GeoIP-guessed country in server logs
- Add support for server stats


https://redd.it/1k2r75z
@r_cpp

Читать полностью…

C++ - Reddit

Brand new CPP programmer, what am I getting into?

I'd like to start by saying I did not choose to learn C++ as my first language, it's just the language that my school is teaching us, and I (as well as the vast majority of students) don't know any others. What I want to know is, what am I getting into with this? What benefits does C++ give over Python, C, Zig, Rust, etc? How hard will it be once I get past the very basics? How hard would it be to learn Objective-C (for GNUStep and MacOS X app dev) and C afterwards? Thanks!

https://redd.it/1k2mmuq
@r_cpp

Читать полностью…

C++ - Reddit

C-style with snake case mindset

About half a year ago I started writing C-style code in C++ using Pascal_Snake_Case (idk if its the real existing name) for user types and snake_case for all other stuff, and SCREAMING_SNAKE_CASE for macros or global constants.
And is actually one of the best combos I've tried so far, at least for solo projects. I mean it became so much easier to write, read and follow code, distinguish actual variable/type names even in text editors where syntax highlighting is minimal. Now when I see local variable name at start of line, I do not expect it to call methods/operators/etc., I expect it to be transformed by assignment family operators which is also reduces the amount of complexity you need to keep in your head, I mean there is no sort of little surprise or unexpected usage or smth like that. The code became predictable and solid in this way.
So I definitely recommend at least to try it. The hardest part would be to use C-style in C++ and hence removing unnecessary abstractions.

https://redd.it/1k2ga5o
@r_cpp

Читать полностью…

C++ - Reddit

Best resource to polish CPP knowledge for intermediate to advanced people?

So I'm going to interview for a teaching assistant position as a programming language instructor (cpp). I've been using cpp for competitive programming for a while now and have a good grip on it but want to perfect my craft for the interview. What books would you guys recommend? Should I go through Bjarne Stroustroup's books or is there any other book you would recommend? I have around 2 weeks to prep for this interview so a smaller primer would be preferred.

https://redd.it/1k2br36
@r_cpp

Читать полностью…

C++ - Reddit

Language support for object retirement?

It is normally the job of the destructor to clean an object at the end if its life, but destructors cannot report errors. There are situations where one may wish to retire an object before its destruction with a function that can fail, and after which the object should not be used any more at all.

A typical example is std::fstream: if I want to properly test for write errors, I have to close it before destruction, because there is no way to find out whether its destructor failed to close it properly. And then it feels like being back to programming in C and losing the advantages of RAII: I must not forget to close the file before returning from the middle of the function, I must not use the file after closing it, etc.

Another typical example would be a database transaction: at the end of the transaction, it can be either committed or aborted. Committing can fail, so should be tested for errors, and cannot be in the destructor. But after committing, the transaction is over, and the transaction object should not be used any more at all.

It is possible to enforce a final call to a retirement function that can fail by using a transaction function that takes a lambda as parameter like this:

client.transaction([](Writable_Database &db)
{
db.new_person("Joe");
});

This may be a better design than having a transaction object in situations where it works, but what if I wish to start a transaction in a function, and finish it in another one? What if I want the transaction to be a member of a class? What if I want to have two transactions that overlap but one is not nested inside the other?

After thinking about potential solutions to this problem, I find myself wishing for better language support for this retirement pattern. I thought about two ways of doing it.

The less ambitious solution would be to have a [[retire]] attribute like this:

class File
{
public:
File(std::string_view name);
void write(const char *buffer, size_t size);
[[retire]] void close();
};

If I use the file like this:

File file("test.txt");
file.write("Hello", 5);
file.close();
file.write("Bye", 3); // The compiler should warn that I am using the object after retirement

This would help, but is not completely satisfying, because there is no way for the compiler to find all possible cases of use after retirement.

Another more ambitious approach would be to make a special "peaceful retirement" member function that would be automatically called before peaceful destruction (ie, not during stack unwinding because of an exception). Unlike the destructor, this default retirement function could throw to handle errors. The file function could look like this:

class File
{
private:
void close();
public:
~File() {try {close();} catch (...) {}} // Destructor, swallows errors
~~File() {close();} // Peaceful retirement, may throw in case of error
};

So I could simply use a File with proper error checking like this:

void f()
{
File file ("test.txt");
file.write("Hello", 5);
if (condition)
return;
file.write("Bye", 3);
}

The peaceful retirement function would take care of closing the file and handling write errors automatically. Wouldn't this be nice? Can we have this in C++? Is there any existing good solution to this problem? I'd be happy to have your feedback about this idea.

It seems that C++ offers no way for a destructor to know whether it is being called because of an exception or because the object peacefully went out of scope. There is std::uncaught_exceptions(), but it seems to be of no use at all (I read https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4152.pdf, but I still think it is buggy: https://godbolt.org/z/9hEo69r5q). Am I missing anything? I am sure more knowledgeable people must have thought about this question before, and I wonder why there seem to be no solution. This would help to implement proper retirement as well: errors

Читать полностью…

C++ - Reddit

Less Slow C++
https://github.com/ashvardanian/less_slow.cpp

https://redd.it/1k2a1oy
@r_cpp

Читать полностью…

C++ - Reddit

The Memory Safety Continuum
https://memorysafety.openssf.org/memory-safety-continuum/

https://redd.it/1jpxxmr
@r_cpp

Читать полностью…

C++ - Reddit

CrashCatch Libary - A Lightweight, Header-Only Crash Reporting Library for C++

Hey r/cpp ,

I’m excited to share **CrashCatch**, a new **header-only** crash reporting library for C++ developers.

# Why CrashCatch?

I created **CrashCatch** to make crash diagnostics easier and more efficient in C++ applications. Instead of manually handling crashes or using complex debuggers, **CrashCatch** automatically generates detailed crash reports, including stack traces, exception details, and memory dumps. It’s designed to be **simple**, **lightweight**, and **cross-platform**!

# Key Features:

* **Cross-Platform**: Supports Windows, Linux, and macOS. (Linux and macOS coming soon)
* **Header-Only**: No dependencies. Just include the header and get started.
* **Minimal Setup**: Works with just a one-liner initialization or auto-init macro.
* **Crash Reports**: Generates `.dmp` and `.txt` crash logs, complete with stack traces and exception details.
* **Symbol Resolution**: Helps developers easily understand where the crash occurred.
* **Easy Integration**: Ideal for integrating into existing C++ projects without much hassle.

# Why use CrashCatch?

* **Efficient Debugging**: Captures meaningful data about the crash without needing a debugger attached.
* **Works in Production**: CrashCatch works even when the application is running in production, helping you diagnose issues remotely.
* **Simple and Lightweight**: It's a single header file with no heavy dependencies—easy to include in your project!

# Get Started:

You can easily get started with **CrashCatch** by including the header file and initializing it in just a few lines of code. Check out the full documentation and code samples on GitHub:
🔗 [CrashCatch GitHub Repository](https://github.com/keithpotz/CrashCatch)

# Future Plans:

* Support for **Linux** and **macOS** crash handling (currently only Windows is fully supported).
* **Remote Uploads**: Secure upload of crash logs.
* **Crash Viewer**: A GUI tool to view crash reports.
* **Symbol Upload Support**: For more accurate stack trace resolution.

I got sick of how cumbersome crash reporting can be in C++ and decided to make my own.


Please be sure to star my github repo to help me out (if you want to of course)

Let me know what you think!

https://redd.it/1jprcj4
@r_cpp

Читать полностью…

C++ - Reddit

Cpp embedded

At what level can I learn cpp for embedded in 5 months as a total beginner? I can dedicate 2 hours every day to studying

https://redd.it/1jponf9
@r_cpp

Читать полностью…

C++ - Reddit

Qt 6.9 released
https://www.qt.io/blog/qt-6.9-released

https://redd.it/1jplwsq
@r_cpp

Читать полностью…

C++ - Reddit

Clang 20 has been released
https://releases.llvm.org/20.1.0/tools/clang/docs/ReleaseNotes.html

https://redd.it/1jpimnn
@r_cpp

Читать полностью…

C++ - Reddit

Coding

How to learn coding ? Can Anybody give .e roadmap

https://redd.it/1jph0ou
@r_cpp

Читать полностью…

C++ - Reddit

Why is there no support for pointers to members of members?

C++ gives us pointers to data members, which give us a way of addressing data members:

struct S { int x; };
int (S::p) = &S::x;
S s = {.x = 1};
std::println("{}", s.
p);

I think of int (S::*) as "give me an S and I'll give you an int". Implementation-wise, I think of it as a byte offset. However, consider the following:

struct Inner { int x; };
struct Outer { Inner i; };
Outer o = {.i = {.x = 1}};
int (Outer::p) = <somehow reference o.i.x>;

This seems reasonable to me, both from an implementation perspective (it's still just an offset) and an interpretation perspective (give me an Outer and I'll give you an int). Is there any technical reason why this isn't a thing? For instance, it could be constructed through composition of member pointers:

// placeholder syntax, this doesn't work
int (Outer::
p) = (&Outer::inner).(&Inner::x);

Implementation-wise, that would just be summing the offsets. Type-checker-wise, the result type of the first pointer and the object parameter type of the second pointer have to match.

https://redd.it/1jp2nsm
@r_cpp

Читать полностью…

C++ - Reddit

Jupyter Notebook

Have you ever tried CPP on jupyter Notebook

https://redd.it/1k3g6m5
@r_cpp

Читать полностью…

C++ - Reddit

I wanna make a friends

We can talk about anything especially c++ or another it discussion

https://redd.it/1k2syxi
@r_cpp

Читать полностью…

C++ - Reddit

What are the differences in math operations from MSVC (windows) to g++ (Linux)


I've heard that C++ math operations can yield different results when compiled with MSVC versus g++, and even between different versions of g++.

Is this true? If so, which operations tend to produce different results, and why does that happen?

Is there a way to ensure that both compilers produce the same results for mathematical operations?


https://redd.it/1k2nqum
@r_cpp

Читать полностью…

C++ - Reddit

Best practices for migrating legacy code bases to modularized import std; ?

I maintain a large, legacy C++ code base. Now that both g++ and cmake support using the modularized standard library, I'm curious to see how that might impact my build times. However, while some of the people who compile this code use compilers and build systems with modularized standard library support, not all do. So, if using `import std;` is a big enough win, I would have to conditionally support it. Generally, the code Includes What We Use, so there are thousands of include sites include-ing specific standard library header files.

Condtionally #include'ing standard library header at each include site seems awful. Forming the set union of all needed header files, and moving all those into a global list of header files, which are only included when building in the tradition way seems even worse.

Are there any best practices for moving from traditional include's to import std? All of the tutorials I've seen assume green-field development. Does anyone have build performance numbers for similar work they could share?

https://redd.it/1k2l13h
@r_cpp

Читать полностью…

C++ - Reddit

Reference/Example of LAPACK Use in C++

Hello!


I would like to use LAPACK in C++ and have only found a (good and useful) stackoverflow answer on how to do this: How to start using lapack in c++


While I'm interested in the API, it is the linking and compilation steps that are least comfortable to me.

Do such references, examples, or docs exist?

https://redd.it/1k2ezyi
@r_cpp

Читать полностью…

C++ - Reddit

that occur in a destructor cannot be thrown, but they could be sent to another object that outlives the object being destroyed. And knowing whether it is being destroyed by an exception or not could help the destructor of a transaction to decide whether it should commit or abort.

Thanks for any discussion about this topic.

https://redd.it/1k29690
@r_cpp

Читать полностью…

C++ - Reddit

Valgrind 3.25 RC1 Announcement

Here is the announcement for Valgrind 3.25 RC1.

Slightly later than originally planned, but the RC1 is finally out!

An RC1 tarball for 3.25.0 is now available at

https://sourceware.org/pub/valgrind/valgrind-3.25.0.RC1.tar.bz2
(md5sum = 2f02fe951278ebde62bba65c3a311a40)
(sha1sum = 3679ddc3237455f07de0ae30f21e947868c2218e)
https://sourceware.org/pub/valgrind/valgrind-3.25.0.RC1.tar.bz2.asc


Please give it a try in configurations that are important for you and
report any problems you have, either on this mailing list, or
(preferably) via our bug tracker at https://bugs.kde.org/enter_bug.cgi?product=valgrind


The NEWS file isn't complete up to date yet, but some highlights:

- Initial RISCV64/Linux support.
- Valgrind gdbserver supports 'x' packets.
- Numerous bug fixes for Illumos.
- --track-fds=yes now treats all inherited file descriptors like
stdin/out/err (0,1,2) and there is a --modify-fds=high option.
- s390x support for various new instructions (BPP, BPRP and NIAI)
- Various new linux syscalls are supported (landlock*, open_tree,
move_mount, fsopen, fsconfig, fsmount, fspick, userfaultfd)
- The Linux Test Project (ltp) is integrated in the testsuite
try 'make ltpchecks' (this will take a while and will point out
various missing syscalls and valgrind crashes!)

Since this RC1 is slightly later than planned and it is a long Easter
weekend for those that celebrate, lets do the RC2 on Wed Apr 25, with
the 3.25.0 final on Fri Apr 27.


The full NEWS file can be found here:
https://sourceware.org/git/?p=valgrind.git;a=blob;f=NEWS;h=e5be7f53a909d171f2b2375903fdddd715f88f3b;hb=HEADHere is the announcement for Valgrind 3.25 RC1.Slightly later than originally planned, but the RC1 is finally out!

An RC1 tarball for 3.25.0 is now available at

https://sourceware.org/pub/valgrind/valgrind-3.25.0.RC1.tar.bz2
(md5sum = 2f02fe951278ebde62bba65c3a311a40)
(sha1sum = 3679ddc3237455f07de0ae30f21e947868c2218e)
https://sourceware.org/pub/valgrind/valgrind-3.25.0.RC1.tar.bz2.asc


Please give it a try in configurations that are important for you and
report any problems you have, either on this mailing list, or
(preferably) via our bug tracker at https://bugs.kde.org/enter_bug.cgi?product=valgrind


The NEWS file isn't complete up to date yet, but some highlights:

- Initial RISCV64/Linux support.
- Valgrind gdbserver supports 'x' packets.
- Numerous bug fixes for Illumos.
- --track-fds=yes now treats all inherited file descriptors like
stdin/out/err (0,1,2) and there is a --modify-fds=high option.
- s390x support for various new instructions (BPP, BPRP and NIAI)
- Various new linux syscalls are supported (landlock*, open_tree,
move_mount, fsopen, fsconfig, fsmount, fspick, userfaultfd)
- The Linux Test Project (ltp) is integrated in the testsuite
try 'make ltpchecks' (this will take a while and will point out
various missing syscalls and valgrind crashes!)

Since this RC1 is slightly later than planned and it is a long Easter
weekend for those that celebrate, lets do the RC2 on Wed Apr 25, with
the 3.25.0 final on Fri Apr 27.

The full NEWS file can be found here: [https://sourceware.org/git/?p=valgrind.git;a=blob;f=NEWS;h=e5be7f53a909d171f2b2375903fdddd715f88f3b;hb=HEAD](https://sourceware.org/git/?p=valgrind.git;a=blob;f=NEWS;h=e5be7f53a909d171f2b2375903fdddd715f88f3b;hb=HEAD)

https://redd.it/1k2b72o
@r_cpp

Читать полностью…

C++ - Reddit

Took me 6 months but made my first app!
https://www.youtube.com/watch?v=ehGolVAHm8U

https://redd.it/1k25cds
@r_cpp

Читать полностью…

C++ - Reddit

Where do I start?

I want to learn C++ and learn how to integrate it for unreal engine. I'm a ComSci major in the first year and I'm pretty decent with C because that's what out prof has been teaching us, but I asked if he will teach his class C++ and he said no because for 2nd years, he's teaching python. Where do I learn C++ that give assignments too so I can learn and apply what I learned for each C++ topic.

https://redd.it/1jpvftk
@r_cpp

Читать полностью…

C++ - Reddit

C++20 in Chromium (talk series)
https://youtube.com/playlist?list=PL9ioqAuyl6UK-d0CS7KF9ToelBJVzxrkv&amp;si=qd0AWH8DfobdZjAN

https://redd.it/1jpr2sm
@r_cpp

Читать полностью…

C++ - Reddit

The usefulness of std::optional<T&&> (optional rvalue reference)?

Optional lvalue references (std::optional<T&>) can sometimes be useful, but optional rvalue references seem to have been left behind.

I haven't been able to find any mentions of std::optional<T&&>, I don't think there is an implementation of std::optional that supports rvalue references (except mine, opt::option).

Is there a reason for this, or has everyone just forgotten about them?

I have a couple of examples where std::optional<T&&> could be useful:

Example 1:

class SomeObject {
std::string string_field = "";
int number_field = 0;
public:
std::optional<const std::string&> get_string() const& {
return number_field > 0 ? std::optional<const std::string&>{string_field} : std::nullopt;
}
std::optional<std::string&&> get_string() && {
return number_field > 0 ? std::optional<std::string&&>{std::move(string_field)} : std::nullopt;
}
};
SomeObject get_some_object();
std::optional<std::string> process_string(std::optional<std::string&&> arg);

// Should be only one move
std::optional<std::string> str = process_string(get_some_object().get_string());

Example 2:

// Implemented only for rvalue `container` argument
template<class T>
auto optional_at(T&& container, std::size_t index) {
using elem_type = decltype(std::move(container[index]));
if (index >= container.size()) {
return std::optional<elem_type>{std::nullopt};
}
return std::optional<elem_type>{std::move(container[index])};
}

std::vector<std::vector<int>> get_vals();

std::optional<std::vector<int>> opt_vec = optional_at(get_vals(), 1);

Example 3:

std::optional<std::string> process(std::optional<std::string&&> opt_str) {
if (!opt_str.has_value()) {
return "12345";
}
if (opt_str->size() < 2) {
return std::nullopt;
}
(*opt_str)[1] = 'a';
return std::move(*opt_str);
}

https://redd.it/1jpnz3t
@r_cpp

Читать полностью…

C++ - Reddit

C++ Show and Tell - April 2025

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/1j0xv13/c_show_and_tell_march_2025/

https://redd.it/1jpjhq3
@r_cpp

Читать полностью…

C++ - Reddit

Is there any way to stop generating .bat/.sh generator conan files in time of installing conan package from remote repositories (in conan 2.x)?

I am using conan version 2.12 and this command:

conan install <conanfile> -r <repo-name> --output-folder=<outer-folder> --build=missing

This is the sample code:

from conan import ConanFile
from conan.tools.files import copy
from conan.tools.env import Environment
from conan.tools.files import rm
import os

class ConsumerConan(ConanFile):
requires = "hello/5.0@ab/stable"

def layout(self):
self.folders.source = "."
self.folders.build = "build"
self.folders.generators = "generator"

def generate(self):

for dep in self.dependencies.values():
for incdir in dep.cpp_info.includedirs:
copy(self, "*.h", incdir, os.path.join(self.build_folder, "headers"))
copy(self, "*.cpp", incdir, os.path.join(self.build_folder, "src"))
copy(self, "*", incdir, os.path.join(self.build_folder, "package"))
copy(self, "*.h", os.path.join(os.path.dirname(incdir),"foo"), os.path.join(self.build_folder, "all"))
copy(self, "*.h", os.path.dirname(incdir), os.path.join(self.build_folder, "all2"))
copy(self, "*", incdir, os.path.join(self.build_folder, "all3"))

As per my requirements, I have to copy the package content in the build folder. But I want to stop the autogeneration of .bat/.sh files(which will be generated inside the generator folder) without using any extra cleanup python scipt.

Thanks in advance!

https://redd.it/1jphno6
@r_cpp

Читать полностью…

C++ - Reddit

Why No Base::function or Parent::function calling?

I understand C++ supports multiple inheritance and as such there COULD be conceivable manners in which this could cause confusion, but it can already cause some confusion with diamond patterns, or even similar named members from two separate parents, which can be resolved with virtual base class…

Why can’t it just know Parent::function() (or base if you prefer) would just match the same rules? It could work in a lot of places, and I feel there are established rules for the edge cases that appear due to multiple inheritance, it doesn’t even need to break backwards compatibility.

I know I must be missing something so I’m here to learn, thanks!

https://redd.it/1jpcl3j
@r_cpp

Читать полностью…

C++ - Reddit

Evaluate my code design level

#include <iostream>
#include <vector>
#include <functional>
#include <string>

using namespace std;

struct FBodyNodeBase
{
virtual bool CanWork()
{
return true;
}

void ForeachImp(function<void(FBodyNodeBase)> InFunction)
{
InFunction(this);
for (size_t i = 0; i < BodyNodes.size(); i++)
{
BodyNodes[i]->ForeachImp(InFunction);
}
}

vector<FBodyNodeBase
> BodyNodes;
string Name;
};

template<typename T>
struct TBodyNode : public FBodyNodeBase
{
void Foreach(function<void(FBodyNodeBase)> InFunction)
{
Node = (T
)this;
ForeachImp(InFunction);
Node = nullptr;
}

static T Node;
};

template<typename T>
T
TBodyNode<T>::Node = nullptr;

struct FBody : public TBodyNode<FBody>
{
FBody() { Name = "Body"; }
bool Pelvis = false;
};

struct FLeg : public TBodyNode<FLeg>
{
FLeg() { Name = "Leg"; }
bool Ankle = true;
virtual bool CanWork()
{
if (!FBody::Node)
return false;

return FBody::Node->Pelvis;
}
};

struct FFoot : public TBodyNode<FFoot>
{
FFoot() { Name = "Foot"; }
virtual bool CanWork()
{
if (!FLeg::Node)
return false;

return FLeg::Node->Ankle;
}
};

int main()
{
FBody Body = new FBody();
Body->Pelvis = false;

FLeg
Leg = new FLeg();
Leg->Ankle = false;

FFoot Foot = new FFoot();

Body->BodyNodes.push_back(Leg);
Leg->BodyNodes.push_back(Foot);

Body->Foreach([](FBodyNodeBase
Body)
{
cout << Body->Name << (Body->CanWork() ? " Can work" : " Can't work") << endl;
});

delete Body;
delete Leg;
delete Foot;

return 0;
}


https://redd.it/1jopsel
@r_cpp

Читать полностью…
Subscribe to a channel