2016-11-14 53 views
-3

我想要一个函数,将一个值计数到零。另外,我想调用一些代码将哪个类作为模板参数传递。 但这段代码不起作用。请有人可以帮我吗? 非常感谢。C++使用模板函数调用一个类的递归函数

的错误信息是:

“函数模板部分特例 '富< 0,T>' 是不允许的”

class Hello_World 
{ 
    public: 
     void hello(size_t number){ 
      cout << "hello " << number << endl; 
     } 
}; 


template<size_t SIZE, class T> 
void foo() 
{ 
    T t; 
    t.hello(SIZE); 
    foo<SIZE-1, Hello_World>(); 
} 

template<class T> 
void foo<0,T>() 
{ 
    cout << "end." << endl; 
} 

int main() 
{ 
    foo<4,Hello_World>(); 
} 
+1

什么不行,到目前为止你尝试过什么,不是编译,崩溃,...? – Zouch

+0

请提供[MCVE]和错误信息。这段代码不会因为几个原因而编译。 – user463035818

回答

0

不能部分地专门模板函数。将其包装在一个类中:

template <size_t SZ, typename T > 
struct foo_impl 
{ 
    static void call() 
    { 
     T().hello(SZ); 
     foo_impl<SZ-1, T>::call(); 
    } 
}; 

template < typename T > 
struct foo_impl<0,T> 
{ 
    // you get the idea... 
}; 

template <size_t SZ, typename T > 
void foo() { foo_impl<SZ,T>::call(); } 
+0

thanx为您的答案,但此代码不能完全工作,我收到错误消息“'调用'不是'foo_impl <0u,Hello_World>'的成员'foo_impl :: call();” ;我把它称为“foo <3,Hello_World>();” –

+0

@doktormoreau当然你必须实现它。替换:“//你的想法”实现了'call()' – user463035818

+0

好吧,我明白了,它可行,谢谢。 –

0

您不能部分地专门化函数模板。然而,你可以部分地专门化一个仿函数(基本上就像一个函数):

#include <iostream> 

template<size_t SIZE, class T> 
struct foo { 
    void operator()(){ foo<SIZE-1, T>()(); } 
}; 

template<class T> 
struct foo<0,T> { 
    void operator()(){ std::cout << "end." <<std::endl; } 
}; 

int main(){ 
    foo<3,int>()(); 
} 
+0

这个也可以,谢谢。 –