美文网首页
auto & decltype

auto & decltype

作者: 哟嚯嚯嚯嚯 | 来源:发表于2018-12-03 17:35 被阅读0次

使用auto和decltype来实现实参推断时,遇到下面case:

template<typename Iter>
auto sum(Iter begin, Iter end)->decltype(*begin) {
    //decltype(*begin) ret = *begin;
    auto ret = *begin;
    for (Iter it = begin + 1; it < end; ++it) {
        ret += *it;
    }
    //cout << typeid(ret).name() << "    " << ret << endl;
    return ret;
}

int main() {
    vector<int> vec = {5, 2, 3, 4};
    auto s = sum(vec.begin(), vec.end());
    cout << s << endl;
    return 0;
}

执行结果为:

0

如果把sum中的注释的cout打开,输出结果为:

14

在sum函数中,只要在return ret之前调用一次ret,就能得到理想的结果,原因未知。

相关文章

  • auto && decltype

    auto:C++11标准引入的类型说明符,编译器通过初始值来推算变量的类型。因此,auto定义的变量必须有初始值a...

  • auto & decltype

    使用auto和decltype来实现实参推断时,遇到下面case: 执行结果为: 如果把sum中的注释的cout打...

  • C++11中auto和decltype

    C++11中auto和decltype auto和decltype都是C++11中引进来用于自动推断类型的关键字,...

  • C++11常用新特性

    initializer_list auto和decltype (1)初始化区别 auto要求必须初始化,因为aut...

  • C++11的类型推导详解

    auto & decltype 关于C++11新特性,最先提到的肯定是类型推导,C++11引入了auto和decl...

  • C++11拾穗

    C++11新关键字 alignas:指定对齐大小 alignof:获取对齐大小 decltype auto(重新定...

  • 模板函数返回类型的演进

    提纲 c++03: trick 方法 c++11: auto->decltype 组合 c++14: 自动推导模板...

  • C++11——string,vector,数组

    使用auto或decltype作为类型缩写 此处line.size()返回一个string::size_type类...

  • [C++11阅读][3-3-4]decltype类型推导(下)

    cv限制符 decltype可以带走cv限制符,这一点跟auto不同,auto带不走。但cv限制符不会扩散到成员变...

  • 超好用的C++11新特性(二)

    在上一篇文章中,我们讲到了nullptr、auto、decltype、for,得益于这些新特性,我们写出的程序更加...

网友评论

      本文标题:auto & decltype

      本文链接:https://www.haomeiwen.com/subject/dnfucqtx.html