Tutorial by Examples

The keyword auto provides the auto-deduction of type of a variable. It is especially convenient when dealing with long type names: std::map< std::string, std::shared_ptr< Widget > > table; // C++98 std::map< std::string, std::shared_ptr< Widget > >::iterator i = table.fin...
auto can also cause problems where expression templates come into play: auto mult(int c) { return c * std::valarray<int>{1}; } auto v = mult(3); std::cout << v[0]; // some value that could be, but almost certainly is not, 3. The reason is that operator* on valarray gives yo...
The auto keyword by itself represents a value type, similar to int or char. It can be modified with the const keyword and the & symbol to represent a const type or a reference type, respectively. These modifiers can be combined. In this example, s is a value type (its type will be inferred as s...
auto is used in the syntax for trailing return type: auto main() -> int {} which is equivalent to int main() {} Mostly useful combined with decltype to use parameters instead of std::declval<T>: template <typename T1, typename T2> auto Add(const T1& lhs, const T2& rh...
C++14 C++14 allows to use auto in lambda argument auto print = [](const auto& arg) { std::cout << arg << std::endl; }; print(42); print("hello world"); That lambda is mostly equivalent to struct lambda { template <typename T> auto operator ()(const...
Sometimes auto may behave not quite as was expected by a programmer. It type deduces the expression, even when type deduction is not the right thing to do. As an example, when proxy objects are used in the code: std::vector<bool> flags{true, true, false}; auto flag = flags[0]; flags.push_...

Page 1 of 1