Last active
August 10, 2023 18:13
-
-
Save b-epelbaum/14e42e89d7afb4da48315a67c53a588b to your computer and use it in GitHub Desktop.
Embracing Safe C++ examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| template <typename A, typename B, typename Result = decltype(std::declval<const A&>() + std::declval<const B&>())> | |
| Result loggedSum(const A& a, const B& b) | |
| { | |
| Result result = a + b; // no duplication of the decltype expression | |
| LOG_TRACE << a << " + " << b << "=" << result; | |
| return result; | |
| } | |
| //------------------------------------------------------------------- | |
| class IdCollection | |
| { | |
| std::vector<int> d_ids; | |
| public: | |
| IdCollection() = default; | |
| IdCollection(const IdCollection&) = default; | |
| // ... | |
| }; | |
| static_assert(std::is_default_constructible<IdCollection>::value, | |
| "IdCollection must be default constructible."); | |
| static_assert(std::is_copy_constructible<IdCollection>::value, | |
| "IdCollection must be copy constructible."); | |
| //---------------------------------------------------------------------- | |
| //Meyers Singleton done properly | |
| static Logger& getLogger() | |
| { | |
| static std::aligned_storage<sizeof(Logger), alignof(Logger)>::type buf; | |
| static Logger& logger = *new(&buf) Logger("log.txt"); // allocate in place | |
| return logger; | |
| } | |
| ///--------------------------------------------------------------- | |
| /////////////// piecewise construct https://www.cppstories.com/2023/five-adv-init-techniques-cpp/ | |
| #include <string> | |
| #include <map> | |
| struct Key { | |
| Key(int a, int b) : sum(a + b) {} | |
| int sum; | |
| bool operator<(const Key& other) const { | |
| return sum < other.sum; | |
| } | |
| }; | |
| struct Value { | |
| Value(const std::string& s, double d) : name(s), data(d) {} | |
| std::string name; | |
| double data; | |
| }; | |
| int main() { | |
| std::map<Key, Value> myMap; | |
| // doesn't compile: ambiguous | |
| // myMap.emplace(3, 4, "example", 42.0); | |
| // works: | |
| myMap.emplace( | |
| std::piecewise_construct, | |
| std::forward_as_tuple(3, 4), | |
| std::forward_as_tuple("example", 42.0) | |
| ); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment