首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归、可变模板函数

递归、可变模板函数
EN

Stack Overflow用户
提问于 2018-05-11 14:56:04
回答 2查看 94关注 0票数 0

我知道我可以使用常规的可变函数来做到这一点,但我想用模板来做到这一点。我的(C++17)编译器不会同意它。

代码语言:javascript
复制
#include <cstdint>

unsigned int fct(unsigned int k)
{
    return k;
}

template<std::size_t First, std::size_t... Other>
unsigned int fct(unsigned int k)
{
    return First * fct<Other...>(k);
}

int main(void)
{
    //const auto k = fct<3u, 5u, 7u>(2u);
    return 0;
}

上面的代码编译正常。但是,如果我选择取消对k声明的注释,编译将失败,并显示以下报告:

代码语言:javascript
复制
foo.cpp: In function ‘int main()’:
foo.cpp:17:13: warning: unused variable ‘k’ [-Wunused-variable]
  const auto k = fct<3u, 5u, 7u>(2u);
             ^
foo.cpp: In instantiation of ‘unsigned int fct(unsigned int) [with     long unsigned int First = 7; long unsigned int ...Other = {}]’:
foo.cpp:11:30:   recursively required from ‘unsigned int fct(unsigned int) [with long unsigned int First = 5; long unsigned int ...Other = {7}]’
foo.cpp:11:30:   required from ‘unsigned int fct(unsigned int) [with long unsigned int First = 3; long unsigned int ...Other = {5, 7}]’
foo.cpp:17:35:   required from here
foo.cpp:11:30: error: no matching function for call to ‘fct<>(unsigned int&)’
  return First * fct<Other...>(k);
                 ~~~~~~~~~~~~~^~~
foo.cpp:9:14: note: candidate: template<long unsigned int First, long unsigned int ...Other> unsigned int fct(unsigned int)
 unsigned int fct(unsigned int k)
              ^~~
foo.cpp:9:14: note:   template argument deduction/substitution failed:
foo.cpp:11:30: note:   couldn't deduce template parameter ‘First’
  return First * fct<Other...>(k);
                 ~~~~~~~~~~~~~^~~

我怎么才能让它工作呢?我认为创建一个非模板fct()就可以完成这项工作。

EN

回答 2

Stack Overflow用户

发布于 2018-05-11 19:50:46

它应该是:

代码语言:javascript
复制
template<std::size_t First>
unsigned int fct(unsigned int k)
{
    return First * k;
}

template<std::size_t First, std::size_t Second, std::size_t... Other>
unsigned int fct(unsigned int k)
{
    return First * fct<Second, Other...>(k);
}

请在wandbox上查看。另一种选择是this,正如@chtz在对答案的评论中所建议的那样。

问题是下面的函数不是函数模板:

代码语言:javascript
复制
unsigned int fct(unsigned int k)
{
    return k;
}

因此,当Other...是一个空的参数包时,您的调用等同于:

代码语言:javascript
复制
return First * fct<>(k);

但它不符合你的任何定义。想想看:

  • 第一个函数不是模板函数,因此不匹配。
  • 第二个函数至少需要一个参数,因此不匹配。

这样就产生了错误。

票数 1
EN

Stack Overflow用户

发布于 2018-05-11 20:02:17

由于问题被标记为C++17,您可能希望尝试新引入的fold expression (live)。

代码语言:javascript
复制
#include <cstdint>
#include <iostream>

template <std::size_t... Args>
auto fct(std::size_t k) noexcept {
  return (k * ... * Args);
}

int main() {
  std::cout << fct<>(1) << std::endl;
  std::cout << fct<2, 3>(1) << std::endl;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50286686

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档