关于模板替换相关的规则
Things to Remember
• During template type deduction, arguments that are references are treated as
non-references, i.e., their reference-ness is ignored.
• When deducing types for universal reference parameters, lvalue arguments get
special treatment.
• When deducing types for by-value parameters, const and/or volatile arguments
are treated as non-const and non-volatile.
• During template type deduction, arguments that are array or function names
decay to pointers, unless they’re used to initialize references.
理解auto
Things to Remember
• auto type deduction is usually the same as template type deduction, but auto
type deduction assumes that a braced initializer represents a std::initial
izer_list, and template type deduction doesn’t.
• auto in a function return type or a lambda parameter implies template type
deduction, not auto type deduction.
上面的规则解释了为啥下面的用法是错误的:
std::vector<int> v;
…
auto resetV =
[&v](const auto& newValue) { v = newValue; }; // C++14
…
resetV({ 1, 2, 3 }); // error! can't deduce type
// for { 1, 2, 3 }
关于decltype
decltype 的作用
Given a name or an expression, decltype tells you the name’s or the expression’s type.
decltype 的用法
Things to Remember
• decltype almost always yields the type of a variable or expression without
any modifications.
• For lvalue expressions of type T other than names, decltype always reports a
type of T&.
• C++14 supports decltype(auto), which, like auto, deduces a type from its
initializer, but it performs the type deduction using the decltype rules.
需要注意的地方:
operator[] on a container of objects of type T typically returns a T&. This is the case
for std::deque, for example, and it’s almost always the case for std::vector. For
std::vector
returns a brand new object.
也就是:
1. 数组\vector 等容器的[]操作符返回的是&类型;
2. std::vecotr
auto differs with Template
So the only real difference between auto and template type deduction is that auto
assumes that a braced initializer represents a std::initializer_list, but template
type deduction doesn’t.
各种指针系列
smart pointer
share pointer
unique pointer
std::unique_ptr comes in two forms, one for individual objects (std::unique_ptr
lambda
lambda只是一段代码,集函数定义和引用于一体。实例“
std::find_if(container.begin(), container.end(),
[](int val) { return 0 < val && val < 10; });
A closure is the runtime object created by a lambda. Depending on the capture
mode, closures hold copies of or references to the captured data.
lambda 也可以拷贝、赋值,实例如下:
“`
{
int x; // x is local variable
…
auto c1 = // c1 is copy of the
[x](int y) { return x * y > 55; }; // closure produced
// by the lambda
auto c2 = c1; // c2 is copy of c1
auto c3 = c2; // c3 is copy of c2
…
}
“`