☕ Buy Me Coffee
← Back to Feed

The Power and Pitfalls of auto

Type deduction in C++ has evolved significantly. The auto keyword (since C++11) is the most prominent feature, allowing the compiler to deduce the type of a variable from its initializer.

Type Deduction Rules

The rules for auto are virtually identical to template type deduction. However, auto deduction treats braced-init-lists as std::initializer_list, which template deduction does not.

auto x = 27;           // x is int
const auto cx = x;     // cx is const int
const auto& rx = x;    // rx is const int&

Decltype(auto) (C++14)

While auto follows template deduction (and thus strips away references and top-level const), decltype(auto) deduces the exact type including references.

int x = 0;
int& getRef() { return x; }

auto a = getRef();        // a is int (copy)
decltype(auto) b = getRef(); // b is int& (reference)

Generic Lambdas (C++14)

You can use auto in lambda parameters to create generic lambdas.

auto adder = [](auto a, auto b) { return a + b; };
adder(5, 10);      // int version
adder(1.5, 2.0);   // double version

// FEEDBACK_LOOP.exe

0.0 / 5.0
FROM 0 PEERS
→ Login to rate