Variable number of arguments in C++?

In C++11 you have two new options, as the Variadic arguments reference page in the Alternatives section states: Variadic templates can also be used to create functions that take variable number of arguments. They are often the better choice because they do not impose restrictions on the types of the arguments, do not perform integral … Read more

Case-insensitive string comparison in C++ [closed]

Boost includes a handy algorithm for this: #include <boost/algorithm/string.hpp> // Or, for fewer header dependencies: //#include <boost/algorithm/string/predicate.hpp> std::string str1 = “hello, world!”; std::string str2 = “HELLO, WORLD!”; if (boost::iequals(str1, str2)) { // Strings are identical }

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

Use rfind overload that takes the search position pos parameter, and pass zero for it: std::string s = “tititoto”; if (s.rfind(“titi”, 0) == 0) { // pos=0 limits the search to the prefix // s starts with prefix } Who needs anything else? Pure STL! Many have misread this to mean “search backwards through the … Read more

Define preprocessor macro through CMake?

For a long time, CMake had the add_definitions command for this purpose. However, recently the command has been superseded by a more fine grained approach (separate commands for compile definitions, include directories, and compiler options). An example using the new add_compile_definitions: add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION}) add_compile_definitions(WITH_OPENCV2) Or: add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION} WITH_OPENCV2) The good part about this is that it circumvents … Read more

C++ unordered_map using a custom class type as the key

To be able to use std::unordered_map (or one of the other unordered associative containers) with a user-defined key-type, you need to define two things: A hash function; this must be a class that overrides operator() and calculates the hash value given an object of the key-type. One particularly straight-forward way of doing this is to … Read more

How to implement the factory method pattern in C++ correctly

First of all, there are cases when object construction is a task complex enough to justify its extraction to another class. I believe this point is incorrect. The complexity doesn’t really matter. The relevance is what does. If an object can be constructed in one step (not like in the builder pattern), the constructor is … Read more