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.


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);

C++11: std::tuple

A tuple is a C++11 construction and it is built heavily on variadic templates.

A tuple is a variadic class template that stores an unlimited set of values of different types, defined when instantiating the tuple; for example:

tuple<int, int> x;

will store 2 integers.

tuple<string, int, bool> y;

will store one string, one integer and one boolean and so on.

Continue reading “C++11: std::tuple”

C++: Smart pointers, part 3: More on unique_ptr

This is the third post of several posts I wrote related to smart pointers:

  1. Smart pointers
  2. unique_ptr
  3. More on unique_ptr
  4. shared_ptr
  5. weak_ptr

Ok, here I am going to write about two other features that unique_ptr has that I did not mention in my last post.

unique_ptr default behavior consists on take ownership of a pointer created with new and that would normally be released with delete.

Continue reading “C++: Smart pointers, part 3: More on unique_ptr”