模板专业化的情况下,如果有变态模板功能

Template specialization in case of variadic template function

本文关键字:功能 专业化 情况下 如果      更新时间:2023-10-16

i具有此功能,它是一个变异模板函数:

template<uint C>
double foo(){
    double cpt = 1;
    for(uint i=0; i<10; i++){
        cpt += i*C; 
    }
    return cpt;
}
template<uint C1, uint C2, uint... CCs>
double foo(){
    double cpt = 1;
    for(uint i=0; i<10; i++){
        cpt += i*C1;    
    }
    return cpt + foo<C2, CCs...>();
}

它可以按预期完美地工作,但我认为这不是做我想做的事情的正确方法。我试图写这样的东西:

double foo(){
    return 0;
}
template<uint C1, uint... CCs>
double foo(){
    double cpt = 1;
    for(uint i=0; i<10; i++){
        cpt += i*C1;    
    }
    return cpt + foo<CCs...>();
}

但是我有错误 no matching function for call foo() note: couldn't deduce template parameter C1。我还尝试了第一个foo函数的template <typename T>,但我的错误也相同。

有人知道为什么吗?我使用的是g 5.4与-std = c 11和-o3旗。

最终迭代将调用foo<>()。它不匹配double foo() { … },因为它不是模板功能。

您无法使用

修复它
template <typename T>
double foo() {
    return 0;
}

因为无法推导T

但是您 can T提供默认值,以便foo<>()变得有效:

template <typename T = void>   // <---
double foo() {
    return 0;
}