#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
void someFunc(){
}
template<typename T>
void f0(T value){
}
template<typename T>
void f(std::initializer_list<T> value){
}
int main() {
auto x = 5;
const auto cx = x; //既非指针也非引用
const auto &rx = x; //const 引用
const auto *ptx = &x;//const 指针
auto &rx1 = x; //引用
auto *ptx1 = &x;//指针
auto&& uref1 = 5; //右值
auto&& uref2 = x; // x是左值,
auto&& uref3 = cx;
auto&& uref4 = rx;
auto func1 = someFunc; //退化为函数指针
auto& func2 = someFunc; // 函数引用
const char text[]="xi men 吹雪";
auto arr1 = text;//退化为指针
auto & arr2 = text;//带长度的数组
//c98语法
auto x1 = 27;
auto x2(27);
//c11语法
auto x3={27};
auto x4{27};
//c11 语法
auto x5={1,2,3};
//error: deduced conflicting types ('int' vs 'double') for initializer list element typeauto x6={1,2,3.1};
// auto x6={1,2,3.1};
f({1,2,3,4});
//auto与模板推导的唯一区别:模板无法使用{}
//f1({11});//error: use of undeclared identifier 'f1' f1({11});
//f1({11,2});//error: use of undeclared identifier 'f1' f1({11,2});
}
编译生成的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
void someFunc()
{
}
template<typename T>
void f0(T value){
}
template<typename T>
void f(std::initializer_list<T> value){
}
/* First instantiated from: insights.cpp:51 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
void f<int>(std::initializer_list<int> value)
{
}
#endif
int main()
{
int x = 5;
const int cx = x;
const int & rx = x;
const int * ptx = &x;
int & rx1 = x;
int * ptx1 = &x;
int && uref1 = 5;
int & uref2 = x;
const int & uref3 = cx;
const int & uref4 = rx;
using FuncPtr_33 = void (*)();
FuncPtr_33 func1 = someFunc;
void (&func2)() = someFunc;
const char text[14] = "xi men \345\220\271\351\233\252";
const char * arr1 = text;
char const (&arr2)[14] = text;
int x1 = 27;
int x2 = 27;
std::initializer_list<int> x3 = std::initializer_list<int>{27};
int x4 = {27};
std::initializer_list<int> x5 = std::initializer_list<int>{1, 2, 3};
f(std::initializer_list<int>{1, 2, 3, 4});
return 0;
}
auto | 推导 |
---|---|
auto x = 5; | int x = 5; |
const auto cx = x | const int cx = x; |
const auto *ptx = &x | const int * ptx = &x; |
auto &rx1 = x; | int & rx1 = x; |
auto *ptx1 = &x; | int * ptx1 = &x; |
auto&& uref1 = 5; | int && uref1 = 5; |
auto&& uref2 = x; | int & uref2 = x; |
auto&& uref3 = cx; | const int & uref3 = cx; |
auto&& uref4 = rx; | const int & uref4 = rx; |
auto func1 = someFunc; | using FuncPtr_33 = void (*)();FuncPtr_33 func1 = someFunc; |
auto& func2 = someFunc; | void (&func2)() = someFunc; |
auto arr1 = text; | const char * arr1 = text; |
auto & arr2 = text; | char const (&arr2)[14] = text; |
auto x3={27}; | std::initializer_list x3 = std::initializer_list{27}; |