C features and usage - lg8888/C-Notes GitHub Wiki
Feature list is based on modern-cpp-features
##C++17 features
-
template parameter deduction This is feature make code easier to read and write. before c++17, this can be achieved by helper template functions that returns fully defined template type. e.g. std::make_tuple() is such helper function
-
non-type template parameters with auto not a big deal here.
-
folding expression save the hassle of specializing terminating case. e.g. sum(1, 2, 3.0) doesn't require a specialization of sum() { return 0;}
-
Lambda capture this by value supports: *this {} in addition to current this{} not a big deal. alternatively, use helper function
-
inline variable inline variable can't be in block scope, thus must be global. this might be useful to make related static variables be located together. alternative: attribute ((section ("section name"))
-
structured binding more readable way to return multiple variables from function: auto [x,y] = position(); alternative: int x,y; std::tie(x,y) = position(); //have to define types, and default construct before std::tie() call
-
initialization for if/switch block not a big deal. currently you have to define explicit scope. but new syntax looks ugly
-
constexpr if extremely useful! avoid the ugly enable_if and all other tricks for specializing template functions ! only the "true" branch of statements need to be well formed. the discarded branch can call to none-existing functions. e.g.
if constexpr ( true ) {
return true;
} else {
return T::abc();
}}}
c++17 stl
- std::invoke : replacement of std::bind, instead of create a lambda, just call it directly
- std::apply : same as std::invoke( call, std::make_tuple( ... ))
- splice std::map and std::set ( member function: extract merge )
c++14 features
- generic lambda allow auto in lambda parameter list. i.e. templatize lambda this allows lambda to be template function
- named lambda capture allows "partial" capture. e.g. [name = emp.name] //avoid capture the whole emp object this also allows capture by move. e.g. [ o2 = std::move(o1)] //o1 be moved into o2
- auto return type allow simpler lambda impl if it needs to call other lambda/template functions. alternatively, use decltype to declare return types
- decltype(auto) keep the reference and const-ness of auto deduced return type
- relaxed constexpr function it can use almost whatever is known to the compiler at compile time
- variable template slightly simpler to use than wrapping type in a struct
##C++11 features
- rvalue the key to understand rvalue is:
- lvalue is variable with accessible memory address or name, rvalue is everything else
- lvalue can match: T & , T const & , but not T &&
- rvalue can match: T const &, T&&, but not T &
- rvalue reference T && is rvalue only if it doesn't have a name. i.e. when used as function parameter it's lvalue