C++11特性--auto,decltype,返回类型后置,using=,nullptr

来源:互联网 发布:资产配置贡献率算法 编辑:程序博客网 时间:2024/06/18 06:34
1.auto
  *C++11将其用于实现自动类型推断(这要求显式初始化,让编译器将变量类型设置为初始值的类型)
   void fun(int x)
{
cout<<"int fun(int x): "<<endl<<x<<endl;
}

 int main()
 {
 
    auto x=1;
    auto px=&x;
    
    auto pf=fun;
//等效于void (*pf)(int);pf=fun; 
    cout<<x<<endl;
    cout<<*px<<endl;
    (*pf)(2);       
   
    return 0;
 }



output:


int fun(int x):
2



 应用于STL可以简化模板声明
 int main()
 {
 
  vector<int> vec{1,2,3,4,5} ;
for(auto p=vec.begin();p!=vec.end();p++)
//auto p=vec.begin()等效于vector<int>::iterator p=vec.begin();
 {
 cout<<*p<<ends;//1 2 3 4 5
 }   
return 0;
 }




2.decltype
   *将变量的类型声明为表达式指定的类型
    格式:
      decltype{expr} var;
  Example:
   int main()
{
  decltype(1+1.111) x;
//x为double类型 
  x=3.14;
  cout<<x<<endl;
//3.14
 
  return 0;



  decltype应用于模板
  Example:
   template<class T1,class T2>
 void add(T1 v1,T2 v2)
 {
  decltype(v1*v2) res;
//res的类型将根据v1,v2的类型而推断
 res=v1+v2;
 cout<<res<<endl;
 }
 
int main()
{
  add(1,3.14);//4.14
 
  return 0;



3.返回类型后置
  *在函数名和参数列表后面指定返回类型
  *auto返回值占位,与decltype配合使用,用于返回值类型后置时的占位。
 
  Example:
  template<class T1,class T2>
  auto add(T1 v1,T2 v2)->decltype(v1*v2)
  {
      return v1+v2;
   }
 
int main()
{
  cout<<add(1,3.14);
//4.14
 
  return 0;

 
  
4.模板别名:using=
  Example:
  int main()
{
vector<int> vec{1,2,3};
using it_type = vector<int>::iterator;
for(it_type it = vec.begin();it!=vec.end();it++)
{
cout<<*it<<ends;
//1 2 3
}
  
    return 0;





 *using= 与typedef的区别
  using=可用于模板部分具体化,而typdef不能

template<class U,class V>

 class A
 {
  public:
   A(U i,V j):x(i),y(j)
   {
   }
   void fun()
  {
  cout<<"x: "<<x<<endl;
  cout<<"y: "<<y<<endl;
  }
private:
  U x;
  V y;
 };


template<class T>
  using u_A=A<T,int>;
  
int main()
{
   
  
  u_A<string> a("hello",100);
  a.fun();
  
   return 0;



output:
 x: hello
 y: 100






5.nullptr空指针
  *nullptr是指针类型,不能转换为整型
  *nullptr==0为true(C++11仍然允许使用0表示空指针
  int main()
{
  int *p=nullptr;
  cout<<(p==0)<<endl;//1
  
  return 0;





 
原创粉丝点击