Skip to content

Instantly share code, notes, and snippets.

@fxfactorial
Created June 10, 2018 18:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fxfactorial/d38e09e676f060280c8dd681b168d8ad to your computer and use it in GitHub Desktop.
Save fxfactorial/d38e09e676f060280c8dd681b168d8ad to your computer and use it in GitHub Desktop.
Destructuring and Tighter scopes with C++17
// clang++ -ggdb -std=c++17 -fsanitize=address src/cool-features.cpp -o T
#include <cstdio>
#include <map>
#include <string>
#include <tuple>
using namespace std;
class record {
public:
record(string a, string b) : result(a + "-" + b) {}
string result;
};
int main() {
const map<string, record> m = {{"Hello", {"A", "B"}}, {"Bar", {"C", "D"}}};
for (const auto &[key, record] : m) {
printf("Hello %s\n", record.result.c_str());
}
if (auto itr(m.find("Bar")); itr != m.end()) {
const auto [key, record] = *itr;
printf("Iterator dereference is valid here: %s\n", record.result.c_str());
} else {
// Couldn't find so can't use *itr here
}
enum class Colors { Red, Blue };
auto producer = []() { return Colors::Red; };
switch (auto result(producer()); result) {
case Colors::Red:
return printf("Got red\n");
case Colors::Blue:
return printf("Got Blue\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment