C++11特性(8):追踪返回类型、范围for

#include <iostream>
#include <vector>
#include <algorithm>
 
//追踪返回类型
template<typename T1, typename T2>
auto Sum(const T1 &t1, const T2 &t2) ->decltype(t1 + t2)
{
     return (t1 + t2);
}

template<typename T1, typename T2>
auto Mul(const T1 & t1, const T2 & t2) ->decltype(t1 * t2)
{
     return (t1 * t2);
}
 
class OuterType
{
     struct InnerType{ int i; };
     InnerType GetInnerType();
     InnerType it;
};
//这里OuterType::InnerType就可以省略为InnerType
auto OuterType::GetInnerType() -> InnerType
{
     return it;
}
 
int(*(*fp())())(){return nullptr; }
//auto(*)() -> int(*)()
//auto fp1() -> auto(*)() -> int(*)()
auto fp1() -> auto(*)() -> int(*)()
{
     return nullptr;
}
 
double foo(int a)
{
     return (double)a + 0.1;
}
int foo(double a)
{
     return (int)a;
}
template<typename T>
auto PreFoo(T t) -> decltype(foo(t))
{
     return foo(t);
}
 
int main()
{
     auto a = 3;  //int
     auto b = 4L; //long
     auto c = 3.14; //double
     auto d = Sum(a, b);
     auto e = Mul(d, c);
     std::cout << typeid(d).name() << std::endl; //long
     std::cout << typeid(e).name() << std::endl; //double
 
     std::cout << std::is_same<decltype(fp), decltype(fp1)>::value << std::endl; //1
 
     std::cout << PreFoo(2) << std::endl; //2.1
     std::cout << PreFoo(1.4) << std::endl; //1

    //基于范围的for循环
     int ar[] = { 1, 2, 3, 4, 5 };
     std::vector<int> iv(ar, ar + 5);
     for (auto& i : iv)
          i *= 2;
     //2 4 6 8 10
     for (auto i : iv)
          std::cout << i << " ";
     //std::for_each(iv.begin(), iv.end(), [](const int i){std::cout << i << " "; });
     std::cout << std::endl;
     return 0;
}

====================打个广告,欢迎关注====================

QQ:412425870
csdn博客:
http://blog.csdn.net/caychen
码云:
https://gitee.com/caychen/
github:
https://github.com/caychen

点击群号或者扫描二维码即可加入QQ群:

328243383(1群)



点击群号或者扫描二维码即可加入QQ群:

180479701(2群)



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值