c++ - 递归的可变参数模板函数

标签 c++ templates variadic-templates c++17 template-meta-programming

<分区>

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

#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 的声明,编译将失败并显示以下报告:

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() 就可以完成这项工作。

最佳答案

应该是:

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 在对答案的评论中所建议的那样。


问题是以下函数不是函数模板:

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

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

return First * fct<>(k);

但它不符合您的任何定义。想一想:

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

因此错误。

关于c++ - 递归的可变参数模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50286686/

相关文章:

c++ - 如何将值输出到 C++11 中的流元组

c# - C++ 文件输入输出错误?

c++ - 尝试在游戏中使用四叉树进行碰撞检测

c++ - 使用 C++ WINSOCK(TCP、SSL)发送电子邮件

c++ - 我们如何使用模板参数类型的变量?

C++ 可变参数模板 : can't match function

c++ - 如何将任意数量的参数传递给 C++ 模板函数?

c++ - 为 sf::String 使用字符串文字时出现链接器错误

java - Apache Velocity 模板中自定义对象类的使用方法

c++ - 带有通用格式说明符的 Printf