Skip to content

Commit be375d6

Browse files
committed
Adding folding expressions example
1 parent 2fa9a1d commit be375d6

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

C++17/CMakeLists.txt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
set(CMAKE_CXX_STANDARD 17)
2+
set(CMAKE_CXX_STANDARD_REQUIRED ON)
3+
4+
file(GLOB CPP_FILES "*.cpp")
5+
6+
foreach(CPP_FILE ${CPP_FILES})
7+
get_filename_component(TARGET_NAME ${CPP_FILE} NAME_WE)
8+
9+
add_executable(${TARGET_NAME} ${CPP_FILE})
10+
11+
add_test(NAME ${TARGET_NAME} COMMAND ${TARGET_NAME})
12+
endforeach()

C++17/fold_expressions.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//#include <print> // Needs to be included if we are using C++23 print function
2+
#include <iostream>
3+
#include <vector>
4+
#include <set>
5+
#include <string>
6+
7+
//size_t... I is a std::integer_sequence whose values are specified by a non-type template
8+
template<typename TupleT, size_t... IdxT>
9+
void print(const TupleT& tupl, std::index_sequence<IdxT...>){
10+
//This experssion (..., operator) folds the tuple by applying operator to
11+
// each of its elements going from left to right
12+
std::cout << "(";
13+
(..., (std::cout << (IdxT == 0 ? "" : ", ") << std::get<IdxT>(tupl)));
14+
std::cout << ")\n";
15+
}
16+
17+
// This is a non-type template that takes a tuple with multiple arguments of some type T
18+
template<typename... T>
19+
void printTuple(const std::tuple<T...>& tupl){
20+
//std::make_integer_sequence creates a sequence of integers of size equal to the number of arguments of T
21+
print(tupl, std::make_index_sequence<sizeof...(T)>());
22+
}
23+
24+
int main(){
25+
std::vector<std::tuple<std::string>> my_list = {("5","3","1"),("1","3","2"),("3","5","A"),("6","4","5")};
26+
27+
auto a = std::make_index_sequence<4>();
28+
for(auto tupl_ : my_list){
29+
//std::cout << std::fmt("{}", my_list[i]) << std::endl; //For C++20 use format
30+
//print("{}", my_list[i]); // For C++23 use print
31+
printTuple(tupl_);
32+
}
33+
return 0;
34+
}

CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ project(CppExamples LANGUAGES CXX)
44
enable_testing()
55

66
set(SUBDIRS C++11)
7+
set(SUBDIRS C++17)
78

89
foreach(SUBDIR ${SUBDIRS})
910
add_subdirectory(${SUBDIR})

0 commit comments

Comments
 (0)