C++: “auto” return type deduction

Before C++14, when implementing a function template you did not know the return type of your functions, you had to do something like this:

template <typename A, typename B>
auto do_something(const A& a, const B& b) -> decltype(a.do_something(b))
{
  return a.do_something(b);
}

You had to use “decltype” in order to say the compiler: “The return type of this method is the return type of method do_something of object a”. The “auto” keyword used to say the compiler: “The return type of this function is declared at the end”.

Since C++14, you can do something by far simpler:

template <typename A, typename B>
auto do_something(const A& a, const B& b)
{
  return a.do_something(b);
}

In C++14, the compiler deduces the return type of the methods that have “auto” as return type.

Restrictions:

All returned values must be of the same type. My example below does not compile because I am returning an “int” or a “double”.

auto f(int n)
{
	if (n == 1)
		return 1;

	return 2.0;
}

For recursive functions, a return value must be returned before the recursive call in order to let the compiler to know what will be the type of the value to return, as in this example:

auto accumulator(int n)
{
	if (n == 0)
		return 0;

	return n + accumulator(n - 1);
}
Advertisements

C++: “auto” on anonymous functions

C++14 introduced an improvement to the way we can declare anonymous functions (a.k.a. lambda expressions).

For example, before C++14, if you wanted to pass an anonymous function to the sort algorithm, you had to do something like this:

Continue reading “C++: “auto” on anonymous functions”

C++: ‘auto’

The new standard of C++ is being released and it exposes a lot of features. Starting this post, I will write about such new features, how they are used and their benefits.

Some bits of history: The last published C++ standard is called C++03 and was published, oh surprise!, in 2003. Since such day, a lot of compilers implemented the features described by that standard. The standard committee continued to work on the next standard and they codenamed it C++0x. The ‘x’ meant it should have been published between 2003 and 2009 but it was not released in such dates; so, the people started to joke saying the ‘x’ means TEN in roman notation or the same Bjarne Stroustrup joked on it saying the ‘x’ stands for any hexadecimal value ;)
Continue reading “C++: ‘auto’”