在可变参数模板函数的情况下的模板特化

时间:2017-05-03 13:30:46

标签: c++ c++11 templates

我有这个函数,它是一个可变参数模板函数:

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。 我还尝试在第一个template <typename T>函数之上使用foo,但我遇到了同样的错误。

有人知道为什么吗? 我正在使用带有-std = c ++ 11和-O3标志的g ++ 5.4。

1 个答案:

答案 0 :(得分:1)

最后一次迭代将调用foo<>()。它与double foo() { … }不匹配,因为它不是模板函数。

您无法使用

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

因为T无法推断出来。

可以为T提供默认值,以便foo<>()生效:

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