【问题标题】:c++ recursive function with calling a class using a templatefunctionc++递归函数,使用模板函数调用类
【发布时间】:2016-11-14 18:12:14
【问题描述】:

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

错误信息是:

"不允许函数模板偏特化'foo'"

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>();
}

【问题讨论】:

  • 什么不起作用,到目前为止你尝试了什么,是不编译,崩溃,......?
  • 请提供minimal reproducible example 和您收到的错误消息。由于多种原因,此代码无法编译。

标签: c++ templates recursion


【解决方案1】:

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

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(); }

【讨论】:

  • 感谢您的回答,但此代码不能完全正常工作,我收到错误消息“'call' is not a member of 'foo_impl'” for line“foo_impl::call();";我用“ foo(); ”来称呼它
  • @doktormoreau 当然你必须实现它。用call()的实现替换:“//你明白了”
【解决方案2】:

您不能部分特化函数模板。但是,您可以部分特化函子(基本上就像函数一样):

#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>()();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多