Skip to content

Commit 0a48353

Browse files
committed
Adding structured bindings
1 parent be375d6 commit 0a48353

File tree

3 files changed

+50
-3
lines changed

3 files changed

+50
-3
lines changed

C++17/fold_expressions.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
//#include <print> // Needs to be included if we are using C++23 print function
21
#include <iostream>
32
#include <vector>
43
#include <set>
54
#include <string>
5+
//#include <print> // Needs to be included if we are using C++23 print function
66

77
//size_t... I is a std::integer_sequence whose values are specified by a non-type template
88
template<typename TupleT, size_t... IdxT>

C++17/structured_bindings.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
* 3. STRUCTURED BINDINGS:
3+
*
4+
* Structured bindings allow us to unpack tuples, pairs, arrays and other packed structures
5+
* directly into variables to improve code readability.
6+
* They essentially perform tuple decomposition and let us bind the contained values into
7+
* local variables.
8+
*/
9+
#include <iostream>
10+
#include <tuple>
11+
#include <cassert>
12+
13+
struct Point
14+
{
15+
int x;
16+
int y;
17+
int z;
18+
};
19+
20+
std::tuple<int, double, std::string> getValues()
21+
{
22+
return {1, 3.14, "something"};
23+
}
24+
25+
int main()
26+
{
27+
std::cout << "===== Test: Structured Bindings with tuple =====\n";
28+
// This is the strucuted binding part where the lhs is a list of variable names
29+
// and the rhs is the container (in this case a tuple)
30+
auto [num, pi, str] = getValues();
31+
32+
assert(num == 1);
33+
assert(pi == 3.14);
34+
assert(str == "something");
35+
36+
37+
Point p{1, 2, 3};
38+
// here we decompose a Point object into separate variables
39+
auto [a, b, c] = p;
40+
assert(a == 1);
41+
assert(b == 2);
42+
assert(c == 3);
43+
44+
return 0;
45+
}

CMakeLists.txt

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@ project(CppExamples LANGUAGES CXX)
33

44
enable_testing()
55

6-
set(SUBDIRS C++11)
7-
set(SUBDIRS C++17)
6+
set(SUBDIRS
7+
C++11
8+
C++17
9+
)
810

911
foreach(SUBDIR ${SUBDIRS})
1012
add_subdirectory(${SUBDIR})

0 commit comments

Comments
 (0)