[1 使用C++11让程序更简洁] 1.1 类型推导(auto和decltype)

1.1 类型推导

1.1.1 auto类型推导

3. auto的限制

void func(auto a =1) {}    //error: auto不能用于函数参数

struct Foo
{
    auto var = 0;        //error: auto不能用于非静态成员变量
    static const auto var1 = 0;    //ok
}

template <typename T>
struct Bar {};

int main()
{
    int arr[10] = {0};
    auto a = arr;        //ok
    auto r[10] = arr;    //error: auto无法定义数组
    
    Bar<int> bar;
    Bar<auto> bb = bar;    //error: auto无法推导出模板参数

    return 0;
}

4. 何时使用auto

(1)遍历stl容器

int main()
{
    std::map<double, double> result;
    std::map<double, double>::iterator it = result.begin();
    for(; it != result.end(); ++it)
    {
        //...
    }
    return 0;
}
使用auto后:
int main()
{
    std::map<double, double> result;
    for(auto it = result.begin(); it != result.end(); ++it)
    {
        //...
    }
    return 0;
}

(2)在unordermap中查找范围

int main()
{
    std::unordered_multimap<int, int> res;
    ...
    std::pair<std::unordered_multimap<int, int>::iterator,
        std::unordered_multimap<int, int>::iterator>
    range = res.equal_range(key);

    return 0;
}
使用auto后:
int main()
{
    std::unordered_multimap<int, int> res;
    ...   
    auto range = res.equal_range(key);

    return 0;
}

(3)无法知道变量应该被定义成什么类型的情况

template <class A>
void func()
{
    auto val = A::get();
    // ...
}

class Foo
{
public:
    static int get()
    {
        return 0;
    }
};

class Bar
{
public:
    static const char* get()
    {
        return "0";
    }
};

int main()
{
    func<Foo>();
    func<Bar>();
    return 0;
}

若不适用auto,就不得不对func再增加一个模板参数,并在外部调用时手动指定get的返回类型。

1.1.2 decltype关键字

auto修饰的变量必须被初始化,编译器需要通过初始化来确定auto的类型。

若仅需要得到类型,而不需要定义变量时,用decltype关键字。

decltype(exp)

1.1.3 返回类型后置语法----auto和decltype结合使用

泛型编程中,可能需要通过参数的运算来得到返回值的类型。

template <typename R, typename T, typename U>
R add(T t, U u)
{
    return t + u;
}

int a = 1;
float b = 2.0;
auto c = add<decltype(a + b)>(a, b);

我们并不关心a+b的类型,因此只需要通过decltype(a + b)得到返回值类型即可。但如上使用十分不方便。尝试修改:

template <typename T, typename U>
decltype(t + u) add(T u, U u)
{
    return t + u;
}

像上面写编译不过。因为t,u在参数列表里,而C++返回值时前置语法,在返回值定义的时候参数变量还没存在。在C++11中增加了返回类型后置语法,将auto和decltype结合起来完成返回类型的推导。

template <typename T, typename U>
auto add(T t, U u) -> decltype(t + u)
{
    return t + u;
}

再举个例子:

int foo(int& i);
float foo(float& i);

template <typename T>
auto func(T& val) -> decltype(foo(val))
{
    return foo(val);
}

返回值类型后置语法,是为了解决函数返回值类型依赖于参数而导致难以确定返回值类型的问题。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值