auto foo = std::make_shared<Foo>(); // obvious auto foo = bla(); // unclear. don't know which type `foo` has
constsize_t max_size = 100; for ( auto x = max_size; x > 0; --x ) // unclear. could lead to the errors // since max_size is unsigned
std::vector<some_class> v; for ( auto it = v.begin(); it != v.end(); ++it ) // ok, since I know that `it` has an iterator type // (don't really care which one in this context)
除了进行类型推导外,auto也可以用于模板中,以简化麻烦的模板参数:
1 2 3 4 5 6 7 8 9 10 11 12 13
// 不使用cuto, 必须添加Product参数 template <typename Product, typename Creator> voidprocessProduct(const Creator& creator){ Product* val = creator.makeObject(); // do somthing with val }
// 使用auto, 省略Product参数 template <typename Creator> voidprocessProduct(const Creator& creator){ auto val = creator.makeObject(); // do somthing with val }
decltype
decltype与auto相对应, 可以从一个变量或表达式中得到类型:
1 2
int x = 3; decltype(x) y = x;
当上文中的模板需要返回值的时候,可以结合auto和deltype简洁实现:
1 2 3 4 5 6
// 使用auto, 省略Product参数 template <typename Creator> void processProduct(const Creator& creator) -> decltype(creator.makeObject()) { auto val = creator.makeObject(); // do somthing with val }
vector<int> v(10); int a = 0; int b = 1; std::generate(v.begin(), v.end(), [&a, &b] { int value = b; b = b + a; a = value; return value; }); // 此时v {1, 1, 2, 3, 5, 8, 13, 21, 34, 55}