函数模板

 拖尾返回类型:当模板函数的返回值取决于特定的模板形参时,可以使用 auto 关键字指定返回类型,然后在函数头的 -> 后使用 decltype 操作符来定义返回类型。

template<class T1,class T2>
auto product(T1 a[], T2 b[], int count)->decltype(a[0] * b[0])
{
    decltype(a[0] * b[0]) sum {};
    for (int i = 0; i < count; ++i)
    {
        sum += a[i] * b[i];
    }
    return sum;
}

int main(int argc, char* argv[])
{
    int a[] = { 1, 2, 3 };
    long b[] = { 1, 2, 3 };
    int n = sizeof(a) / sizeof(a[0]);
    auto ret = product(a, b, n); //14
    const char* s = typeid(product(a, b, n)).name(); //long
    return 0;
}

 

decltype(..)是获得一个表达式的结果值的类型。->后的是函数的返回类型。

 

posted @ 2019-08-31 15:41  htj10  阅读(156)  评论(0编辑  收藏  举报
TOP