Practical C++ 17 features

I am going to write about the practical C++17 features and how to use them in our day to day code. I have separated the ones which are extremely useful for a modern C++ programmer. I made this into various tutorials so that it can be absorbed in modules.  We will start with Structured Bindings. In the first lesson, I will cover the concepts that make the code simple.

For a detailed list of all the features added in C++, check this.  

Tutorial 1

Structured Bindings

In order to return many items we commonly use tuples. When a function returns a tuple to unpack that we use a tie, check this for more details. It can be used to unpack a tuple into different variables.

std::tuple<int, float, bool> GetMyTuple()
{
	int a = 100; 
	int f = 20.3; 
	bool isValid = true; 
	return std::make_tuple(a,f,isValid);
}

The return will need the following.

int num, float digits, bool valid; 
std::tie(num, digits, valid ) = GetMyTuple();

In C++17, we can use as follows

auto[num,digits,valid] = GetMyTuple(); 

This will automatically deduce the return into corresponding variables for num, digits and valid which can be used in the program.

Return handler

This can handle return of compound types as well.

#include <set>
#include <string>
#include <iomanip>
#include <iostream>

int main() {
    std::set<std::string, int > myset;
    if (auto [iter, success] = myset.insert("Hello C++17 "); success)
        std::cout << "Insert is successful. The value is " << std::quoted(*iter) << '\n';
    else
        std::cout << "The value " << std::quoted(*iter) << " already exists in the set\n";
}

iter is used for the value and the success indicates whether the insertion into the map was successful or not.

Iteration

Iterating over the map automatically adds the key entry into the key variable and value into the value variable. This is very useful and makes the code more readable and simple to use.

Iterating over a template like map is as follows

#include <string>
#include <iomanip>
#include <iostream>
#include <map>

int main() {
	std::map<std::string, int> myMap;
	myMap["Abc"] = 1;
	myMap["Def"] = 2;
	for (const auto& [key, value] : myMap)
	{
		std::cout << "Person Name : " << key <<  " Person ID  : " << value << std::endl;
	}
}

Next : Direct Initialization

2 thoughts on “Practical C++ 17 features

Comments are closed.