gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:33:51 25 4
gpt4 key购买 nike

<分区>

我知道我可以用一个常规的可变参数函数来做到这一点,但我想用模板来做到这一点。我的 (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() 就可以完成这项工作。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com