码迷,mamicode.com
首页 > 其他好文 > 详细

函数模板

时间:2019-08-31 17:27:06      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:count   eof   函数模板   auto   sum   nbsp   template   const   name   

 

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(..)是获得一个表达式的结果值的类型。->后的是函数的返回类型。

 

函数模板

标签:count   eof   函数模板   auto   sum   nbsp   template   const   name   

原文地址:https://www.cnblogs.com/htj10/p/11439260.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!