-
C++ links
-
C++ Ecosystem: Compilers, IDEs, Tools, Testing and More
- and meson, missed from the above review
-
How to use "--allow-multiple-definition" tl;dr the correct syntax is
-ldflag=-Wl,--allow-multiple-definition ... mylib = shared_library(..., dependencies: [liblog,], ... link_args: '-Wl,--allow-multiple-definition')
- and meson, missed from the above review
-
several GNU make tips
-
CMake
- CMake Cookbook
- An Introduction to Modern CMake
- CGold: The Hitchhiker’s Guide to the CMake
- CMake cheat sheet
- greenfield : start new project with C++/CMake
- vim-cmake-boilerplate
- CMake cannot find GoogleTest required library in Ubuntu
- CMake by Example
add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION}) add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION} WITH_OPENCV2) target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/config $<TARGET_FILE_DIR:${PROJECT_NAME}>/config)
- Executing multiple post build commands in CMake depending on condition
- Copy file from source directory to binary directory using CMake
- why Cmake's “ file(REMOVE_RECURSE [file1 …]) ”does not remove file having *.xxx.yy extension file?
- Backward compatible
add_compile_definitions
- CMake and object libraries
- Problems with directory delimiters turning into backslashes when running cmake
tl;dr
cmake -DCMAKE_CXX_COMPILER:FILEPATH=C:\Game Dev\Tools\MingW-
- Test Fixtures With CMake/CTest
- pybind11Config.cmake helpers
- CMake FindPython3
- Использование Eigen в проектах CMake
-
CppCon 2017: Rong Lu "C++ Development with Visual Studio Code"
-
C++ Development with Visual Studio Code
- 11 Best Programming Fonts
- Comparing the new Cascadia Code font to Fira Code v2
- Fira Code VS Code Instructions
- Daily Dev Tips №96— Visual Studio Code — how to enable this new sexy Fira Code font?
- Представляем шрифт Cascadia Code
- This is a fun, new monospaced font that includes programming ligatures and is designed to enhance the modern look and feel
- Keyboard shortcut for Visual c# block comment in Visual Studio 2015? tl;dr
keyboard shortcut for single line(//....) commenting Ctrl + K + C and uncommenting Ctrl + K + U .
- Using C++ on Linux in VS Code
- C/C++ for VS Code (Preview)
- Configuring C/C++ debugging
- VSC Debugging
- VSC tasks
- How to run a command in Visual Studio Code with launch.json
- Does vscode use workspaceRoot or workspaceFolder?
- How to run Cmake in Visual Studio Code using tasks
- C++ Development using Visual Studio Code, CMake and LLDB
- How to jump to build error in Visual Studio Code?
Switch Between Projects Like A Pro In Visual Studio Code
- 11 Best Programming Fonts
-
Thoughts about Software Development with an eye on the world of modern C++ Programming
- My God, It’s Full Of Stars: The N-Body-Problem Series
- My God, It’s Full Of Stars: And then there was CMake
- My God, It’s Full Of Stars: Testing Point Mass Attraction with Catch2
- My God, It’s Full of Stars: Implementing the implicit Euler-Method with STL
- Introduction into Logging with Loguru
- Using Pointer to Members on STL Algorithms
- Introduction into Logging with Loguru
- Introduction into C++ Builds with Gradle
- A short Introduction into IEEE 754 Floating-Point Model
- Numerical Methods with C++ Part 1: Newton-Cotes Integration
- Numerical Methods with C++ Part 2: Gauss-Legendre Integration
- Numerical Methods with C++ Part 3: Root Approximation Algorithms
- Numerical Methods with C++ Part 4: Introduction Into Decomposition Methods of Linear Equation Systems
-
C
-
C++
-
free modern C++ book: Discovering Modern C++
-
CppCon
-
-
Valery Lesin. C++ In-Depth, 2014
-
The C++ Standards Library for Concurrency and Parallelism http://stellar-group.org/libraries/hpx
-
- tl;dr
- use case in Flexible Collision Library
- don't confuse with export templates
- tl;dr
-
SFINAE
-
enum to string in modern C++11 / C++14 and future C++17 / C++20
-
C++ and multithreading
-
Memory Model
-
Top 20 C++ multithreading mistakes and how to avoid them
tl;dr- Not using
join()
to wait for background threads before terminating an application. - Trying to
join()
a thread that has been previously detached. - Not realizing that
std::thread::join()
blocks the calling thread. - Thinking that thread function arguments are pass by reference by default.
tl;dr usestd::ref()
for passing by reference. - Not protecting shared data or shared resources with a critical section (eg. mutex).
- Forgetting to release locks after a critical section.
- Not keeping critical sections as compact and small as possible.
- Not acquiring multiple locks in the same order.
- Trying to acquire a
std::mutex
twice. - Using mutexes when
std::atomic
types will suffice. - Creating and Destroying a lot of threads directly when using a thread pool is available.
- Not handling exceptions in background threads.
- Using threads to simulate Asyn jobs when
std::async
will do. - Not using
std::launch::async
if asynchronicity is desired. - Calling
.get()
on astd::future
in a time sensitive code path. - Not realizing that an exception thrown inside an async task is propagated when
std::future::get()
is invoked. - Using
std::async
when you need granular control over thread execution. - Creating many more "Runnable" threads than available cores.
- Using
volatile
keyword for synchronization. - Using a Lock Free architecture unless absolutely needed
- Not using
-
Locking and Conditional Variables
- C++11 Multithreading Part 7: Condition Variables Explained
- C++11-concurrency-tutorial-advanced-locking-and-condition-variables
- C++11 concurrency: condition variables
- std::unique_lockstd::mutex or std::lock_guardstd::mutex?
- std::unique_lock vs. от std::lock_guard?
- tl;dr
almost the same, but
lock_guard
has less functionality, locks only once and more preferrable; uselock_guard
unless you need unlocling, forcondition_variable
s thatwait()
ing from sleep.
- tl;dr
almost the same, but
-
http://preshing.com/20130618/atomic-vs-non-atomic-operations/
-
Comparison: Lockless programming with atomics in C++ 11 vs. mutex and RW-locks
-
What is the equivalent of boost::upgrade_to_unique_lock in STL?
-
-
C++11 Tidbits: Template Aliases
template<typename T> class allocator { //... template<typename U> struct rebind { typedef allocator<U> other; }; }; allocator<T>::rebind<U>::other x; // sample usage
can be rewritten
template<typename T> class allocator { //... template<typename U> using rebind = allocator<U>; }; allocator<T>::rebind<U> x; // sample usage
- why
rebind
template <typename T, typename A = std::allocator<T>> class list { struct node { T value; node* next; node* prev; }; using allocator = typename A::template rebind<node>::other; };
- why
-
- tl;dr
template<class T> constexpr T pi = T(3.1415926535897932385); // variable template template<class T> T circular_area(T r) // function template { return pi<T> * r * r; // pi<T> is a variable template instantiation }
-
- tl;dr
// classical template<class InputIt, class T, class BinaryOperation> constexpr // since C++20 T accumulate(InputIt first, InputIt last, T init, BinaryOperation op) { for (; first != last; ++first) { init = op(std::move(init), *first); // std::move since C++20 } return init; } // a variation template<typename T> struct range_value { using type = typename T::value_type; }; template<typename T> struct range_value<T*> { using type = T; }; template <typename I, typename Op> typename range_value<I>::type accumulate(I beg, I end, typename range_value<I>::type unit, Op op) { typename range_value<I>::type acc{unit}; for (auto it = beg; it != end; ++it) { acc = op(acc, *it); } return acc; } int main() { std::list l{1, 2, 3, 4}; std::vector v{1, 2, 3, 4}; float c_array[] = {1.1f, 2.2f, 3.3f, 4.4f}; auto sl = accumulate(std::begin(l), std::end(l), 1, std::multiplies<>{}); auto cl = accumulate(std::begin(c_array), std::end(c_array), 0, std::plus<>{}); auto sv = accumulate(v.begin(), v.end(), 0, std::plus<>{}); }
-
- tl;dr
namespace dispatch { using std::swap; template<class T, class voider = void_t<>> struct has_member_swap : std::false_type { }; template<class T> struct has_member_swap<T, void_t<decltype(noexcept(swap(std::declval<T&>(), std::declval<T&>()))), typename std::enable_if_t<!std::is_array<T>::value>> > : std::integral_constant<bool, std::is_move_assignable<T>::value && std::is_move_constructible<T>::value > { }; template<class T> struct has_member_swap<T, typename std::enable_if_t<std::is_array<T>::value>> : has_member_swap<std::remove_all_extents_t<T>> { }; }
-
What Every C++ Developer Should Know to (Correctly) Define Global Constants
-
Поразрядная сортировка с человеческим лицом Radix sort in C++
-
Fast function to parse strings into double floating-point values
-
selected stackoverflow questions
-
How and why one would use Boost signals2?
- Is boost::signals2 overkill for simple applications?
tl;dr almost 100x performance penalty over plain function call - Conversion of Qt Signals to Boost Signals2
- Making Boost.Signals2 More OOP‐Friendly
- Is boost::signals2 overkill for simple applications?
-
throwing exceptions out of a destructor
- summary:
Throwing an exception out of a destructor is dangerous. If another exception is already propagating the application will terminate.
- "More Effective C++" Item 11: Prevent exceptions from leaving destructors
- summary:
-
What does the explicit keyword in C++ mean?
- dubbed from above link
// Suppose you have a class String: class String { public: String(int n); // allocate n bytes to the String object String(const char *p); // initializes object with char *p }; // Now if you try String mystring = 'x'; // the char 'x' will be implicitly converted to int and then will call the String(int) constructor. // But this is not what the user might have intended. So to prevent such conditions, we shall define the constructor as explicit: class String { public: explicit String (int n); //allocate n bytes String(const char *p); // initialize sobject with string p };
-
C++ convert from 1 char to string?
- tl;dr
char c = 42; std::cout << string(1, c) << std::endl;
-
how to pre-allocate memory for a std::string object?
- tl;dr
// New Test -- the fastest std::string s4; clock_t start4 = clock(); file.seekg(0, std::ios::end); s4.resize(file.tellg()); file.seekg(0, std::ios::beg); file.read(&s4[0], s4.length()); clock_t stop4 = clock();
-
Can a C++ lambda constructor argument capture the constructed variable?
-
generic variadic lambdas
- TL;DR
auto get_item = [&ifs](auto& item) { std::string line; std::getline(ifs, line); std::istringstream iss(line); iss >> item; }; ... get_items(std::ref(params.thorus_params.xfirst), std::ref(params.thorus_params.yfirst));
#include <boost/range/adaptor/map.hpp> #include <boost/range/algorithm/copy.hpp> #include <boost/assign.hpp> #include <boost/algorithm/string/join.hpp> #include <algorithm> #include <iostream> #include <map> #include <vector> int main() { std::map<std::string, std::string> m; m["hello"] = "world"; m["goodbye"] = "now"; std::vector<std::string> o; // boost::copy(m | boost::adaptors::map_keys, std::back_inserter(o)); boost::copy(m | boost::adaptors::map_values, std::back_inserter(o)); std::cout << boost::algorithm::join(o, ", ") << std::endl; }
- boost.histogram bare-bone installation
git clone https://github.com/boostorg/histogram.git git clone https://github.com/boostorg/mp11.git git clone https://github.com/boostorg/callable_traits.git git clone https://github.com/boostorg/assert.git git clone https://github.com/boostorg/throw_exception.git git clone https://github.com/boostorg/core.git git clone https://github.com/boostorg/config.git git clone https://github.com/boostorg/variant2.git
-
Boosting the Accuracy of Differentially Private Histograms Through Consistency
-
Improving Accuracy and Robustness of Self-Tuning Histograms by Subspace Clustering
-
cheat-sheet for callbacks in C++
-
Using std::make_unique with custom deleter on a derived class?
- tl;dr you cannot indicate a custom deleter with the
make_*
helper functions for smart pointers (neither withmake_unique
, nor withmake_shared
). use to explicitly construct your pointer as it follows:If the deleter is not default constructible, you can do this:std::unique_ptr<T, D> ptr{new T{)};
std::unique_ptr<T, D> ptr{new T{}, d};
- tl;dr you cannot indicate a custom deleter with the
-
std::unique_ptr for class data member ABI (Pimpl idiom)
- Move constructor involving const unique_ptr
- Why am I getting compile error “use of deleted function 'std::unique_ptr …”
tl;dr The chief feature of std::unqiue_ptr is that it cannot be copied. That's by design, and the name tells you as much. takestd::unique_ptr<..> const&
-- no copy is needed.
-
unique_ptr, shared_ptr, weak_ptr, or reference_wrapper for class relationships
-
std::call_once()
-
Some tips on iterators
-
C++ specialization
- Function Templates Partial Specialization in C++
- C++ Template specialization for subclasses with abstract base class
template <typename M> struct SetTarget { SetTarget(M* t): target(t) {} M* target; }; template <typename M, typename T, bool = std::is_base_of<OperationMessage, T>::value> struct SetId : public SetTarget<M> { SetId(M* t) : SetTarget<M>(t) {} void operator()(T) { std::cout << "SetId with -1\n"; SetTarget<M>::target->setId(-1); } }; // partial specialization template <typename M, typename T> struct SetId<M, T, true> : SetTarget<M> { SetId(M* t) : SetTarget<M>(t) {} void operator()(T msg) { std::cout << "SetId with msg.getSequence()\n"; SetTarget<M>::target->setId(msg.getSequence()); } };
-
selected boost tips
-
boost property tree
auto dump_vector = [](std::string const& name, auto const& v) { std::cout << name << " : { "; for (auto val : v) { std::cout << val << ", "; } std::cout << "}\n"; }; auto vec = xml_data.get("A.E.S.coeffs", std::vector<float>()); dump_vector("coeffs", vec);
-
A method to list all files in directory and sub-directories using boost and c++
#include <iostream> #include <string> #include <vector> #include <boost/filesystem.hpp> #include <boost/range.hpp> std::vector<std::string> get_file_list(std::string const& path) { std::vector<std::string> files; if (!path.empty()) { boost::filesystem::path dir = "."; boost::filesystem::recursive_directory_iterator it(dir), end; for (auto& entry : boost::make_iterator_range(it, end)) if (boost::filesystem::is_regular(entry)) files.push_back(entry.path().native()); } return files; } int main(int argc, char** argv) { if (argc > 1) { auto file_list = get_file_list(argv[1]); for (auto const& f : file_list) { std::cout << "- " << f << std::endl; } } }
-
-
Can I use std::vector as a template parameter or does it need to be std::vector?
-
REST API
-
XML, HTML and network libraries in C++
- A Cheat Sheet for HTTP Libraries in C++
- Benchmark. Analyzing and Testing Current HTML Parsers TL;DR HTML5Ever is written in Rust:) MyHTML is the fastest; Gumbo is produced by Google
- Parsing HTML with C++: Revisited
- Getting directory listing over http
- Downloading flv from youtube using curlpp on top of curl - video not playing
-
C++11 and semaphores
-
intrusive prt vs.
std::shared_ptr
-
Double-Checked Locking is Fixed In C++11
class smartSingleton { private: static std::mutex _mutex; smartSingleton(); smartSingleton(const smartSingleton& rs); smartSingleton& operator = (const smartSingleton& rs); public: ~smartSingleton(); static std::shared_ptr& getInstance() { static std::shared_ptr instance = nullptr; if (!instance) { std::lock_guard lock(_mutex); if (!instance) { instance.reset(new smartSingleton()); } } return instance; } void demo() { std::cout << "smart pointers # next - your code ..." << std::endl; } };
class Singleton { public: static Singleton & Instance() { // Since it's a static variable, if the class has already been created, // It won't be created again. // And it **is** thread-safe in C++11. static Singleton myInstance; // Return a reference to our instance. return myInstance; } // delete copy and move constructors and assign operators Singleton(Singleton const&) = delete; // Copy construct Singleton(Singleton&&) = delete; // Move construct Singleton& operator=(Singleton const&) = delete; // Copy assign Singleton& operator=(Singleton &&) = delete; // Move assign // Any other public methods protected: Singleton() { // Constructor code goes here. } ~Singleton() { // Destructor code goes here. } // And any other protected methods. }
-
Retiring the Singleton PatternConcrete suggestions for what to use instead
-
C++: Rounding up to the nearest multiple of a number
tl;dr If multiple is a power of 2 (faster in ~3.7 times http://quick-bench.com/sgPEZV9AUDqtx2uujRSa3-eTE80)
int roundUp(int numToRound, int multiple) { assert(multiple && ((multiple & (multiple - 1)) == 0)); return (numToRound + multiple - 1) & -multiple; }
-
Progress Bar
- How to display a progress indicator in pure C/C++ (cout/printf)? tl;dr more neat and nice solution
void printProgressNice (float percentage, int wid = 60) { const char PBFILLER[] = "█"; int val = (int) (percentage * 100); int lpad = (int) (percentage * wid); int rpad = wid - lpad; printf("\r%3d%%[", val); while (lpad--) printf("%s", PBFILLER); while (rpad--) putchar(' '); printf("]"); fflush(stdout); }
-
К тридцатилетию первого C++ компилятора: ищем ошибки в Cfront
-
- juCi++: a lightweight, platform independent C++-IDE with support for C++11, C++14 and C++17 features depending on libclang version.
- Beginning C++20
- Pure Virtual C++ 2020
- C++20: The Big Four
-
CppCon 2020
- Plenary: Performance Matters - Emery Berger - CppCon 2020
- CppCon 2020 Presentation Materials
- Managarm - A Fully Asynchronous Operating System Powered By Modern C++
- The Shapes of Multi-Dimensional Arrays
- std::map<Key,T,Compare,Allocator>::insert_or_assign
- Multi-Level Break in C++ via IIFE
- Recursive Lambdas in C++
- Approximating 'constexpr for'
- Overloading by Return Type in C++ tl;dr
struct to_string_t { std::string_view s; operator int() const; // int from_string(std::string_view s); operator bool() const; // bool from_string(std::string_view s); }; int i = to_string_t{"7"}; bool b = to_string_t{"true"};
-
selected C++ projects
- Curated list of awesome lists Awesome C++
- C++ DataFrame for statistical, Financial, and ML analysis -- in modern C++ using native types and contiguous memory storage, i.e. pandas in C++
- Modern C++ Parallel Task Programming
- Filament is a physically based rendering engine for Android, Windows, Linux and macOS
- digestpp - experimental C++11 header-only message digest library
- {fmt} is an open-source formatting library providing a fast and safe alternative to C stdio and C++ iostreams
- std::format in C++20
- An Extraterrestrial Guide to C++20 Text Formatting
- std::format in C++20
- How to use C++20 modules in GNU g++-11
- cpp-lazy
- indicators - Thread-safe progress bars and spinners
- criterion is a micro-benchmarking library for modern C++
- alpaca - Pack C++ structs into a compact byte-array without any macros or boilerplate code
- FTXUI - Functional Terminal (X) User interface
- Diagon is an interactive interpreter. It transforms markdown-style expression into an ascii-art representation
- C++ UI Libraries
- json (de)serialize
- Memgraph is a streaming graph application platform that helps you wrangle your streaming data, build sophisticated models that you can query in real-time, and develop graph applications
- [Comprehensive C++ Hashmap Benchmarks 2022](https://martin.ankerl.com/2022/08/27/hashmap-bench-01/
-
misc
- ModernCppStarter
- Modern C++ Tutorial: C++11/14/17/20 On the Fly
- Reading TAR files in C++
- Error codes are far slower than exceptions
- Single header implementation of std::expected with functional-style extensions
- C++ Result
- Book: A Complete Guide to Standard C++ Algorithms
- vtable implementation with multiple inheritance
- Python-Like enumerate() In C++17
std::vector<std::string> strings{10, "Hello"}; int main(){ strings[5] = "World"; for(auto const& el: strings| boost::adaptors::indexed(0)) std::cout << el.index() << ": " << el.value() << std::endl; }
- How to find out if there is any non ASCII character in a string with a file path
tl;dr
auto isASCII = [](const std::string& s) -> bool { return !std::any_of(s.begin(), s.end(), [](char c) { return !isascii(static_cast<unsigned char>(c)); }); };
-
Is there a way to use C++ preprocessor stringification on variadic macro arguments?
-
Compilation error related to map and unordered_map: "attempting to reference a deleted function"
-
How to convert errno to exception using <system_error>
#include <system_error> #include <iostream> int main() { std::cout << std::error_code{errno, std::generic_category()}.message() << '\n'; }
-
C++ Annotated June-August 2022: C++23 and C23 News, Language Tips and Tricks, and New Tools Releases
-
-