Monday, July 17, 2017

C++11: noexcept

The ‘noexcept’ keyword is the preferred replacement for the ‘throw()’ exception specification.


C++11: Lambda Expressions: Function Objects

Lambda Expressions can be used in place of function objects. For example, as the comp parameter in the std:: sort() template function.
template
  void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

                      http://www.cplusplus.com/reference/algorithm/sort/

C++11: Lambda Expressions: Capture List

In a lambda expression, “[]” and it’s contents define the capture list.
The following are some variations of the capture list:
[] captures nothing
[&] captures all local variables by reference
[=] captures all local variables by value
[this] captures the current object by reference
[a] captures local variable a by copy
[&a] captures local variable a by reference
Here is an example:
#include
int main()
{
  int local1 = 3;
  int local2 = 4;
  [&](int param1, int param2) {std::cout << param1 << " " << param2 << " "
                                         << local1 << " " << local2 << std::endl;}(1, 2);
  return 0;
}
// Output: 1 2 3 4



C++11: Lambda Expressions: Parameter Passing

The example below shows how to pass parameters to a lambda expression.
#include
int main()
{
  [](int param1, int param2) {std::cout << param1 << " " << param2 << std::endl;}(1, 2);
  return 0;
}
// Output: 1 2



C++11: Lambda Expressions

Lambda Expressions let you define unnamed functions. Here is an example:
#include
int main()
{
  []() {std::cout << 1 << std::endl;}();
  return 0;
}
// Output: 1



C++11: Perfect Forwarding

This is the ability to wrap a function without creating all combinations constness overloads. Here is an example:

#include
template
void func(T i)
{
  std::cout << i << " ";;
}

template
void wrapper_without_perfect_forwarding(T& i)
{
  func(i);
}

template
void wrapper_with_perfect_forwarding(T&& i)
{
  func(std::forward(i));
}

int main()
{
  int variable = 1;
  wrapper_without_perfect_forwarding(variable);
  // wrapper_without_perfect_forwarding(2); // Error: 'void wrapper_without_perfect_forwarding(T &)':
                                                                                  //                   cannot convert argument 1 from 'int' to 'int &'
  wrapper_with_perfect_forwarding(variable);
  wrapper_with_perfect_forwarding(3);

  return 0;
}
// Output: 1 1 3


C++11: Universal Reference

A reference that binds to both lvalues and rvalues. An example of a Universal Reference is an Rvalue Reference to a template type parameter. Scott Meyer invented the term, by the C++ committee prefers the term ‘Forwarding Reference’.