2017-05-03 145 views
0

我有这个功能是AA可变参数模板功能:模板专业化

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函数的顶部,但我有同样的错误。

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

+0

'回报CPT + F ();'能肯定Viridya? – gsamaras

+0

@gsamaras typo抱歉 – Viridya

+0

[OT]:你可以摆脱循环,直接做'return(45 * C1 + 1)+ foo ();' – Jarod42

回答

1

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

使用

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

因为T不能推断你不能修复它。

但是你可以提供T一个默认值,以便foo<>()生效:

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

太棒了。我甚至不知道我们可以为'T'提供一个默认值。谢谢 ! 我曾经尝试类似: 模板 双富(){返回0;} 但它不工作。 – Viridya

+1

@Viridya模板专门化不适用于函数。你需要一个类('template struct Foo ...')。 – kennytm