假设我想定义一个在括号内没有输入参数但在 <>
内的 C++ 函数。争论。我有一个参数包作为输入参数。这意味着我必须编写例如一个函数
int calculate<args...>()
{
return 1 + calculate<some_arg,args...>();
}
还有一个我必须给出的基本案例实现。但是,我遇到了很多编译器错误,因为我不知道如何正确编写这种形式的递归。在上述函数声明之前我必须写什么?template<int... args>
(如果 args 的数据类型是 int;任何其他数据类型也可以采用类似的方式)?或者我必须写什么来避免编译器错误?我也试过template<int some_arg,int... args>
但我也不知道如何处理可变参数模板(如何解压它们)。有什么帮助吗?编辑:
我对一种特殊情况的尝试
template<bool... dg>
int calculate<0>()
{
return 1;
}
错误信息是:错误:“<”标记之前的预期初始化程序
最佳答案
But I don't know also how to deal with variadic templates (how to unpack them). Any help?
从 C++17 开始,您无需求助于递归,但可以使用包扩展:
#include <iostream>
template<int ...Args>
constexpr int calculate() {
return (Args + ...);
}
int main() {
std::cout << calculate<1, 2, 3>(); // 6
}
如果您想允许其他类型的非类型模板参数,您可以为非类型模板参数使用占位符类型 ( auto
),这也是 C++17 的一个特性:template<auto ...Args>
constexpr auto calculate() {
return (Args + ...);
}
由于您不能部分特化函数模板,因此如果您想为不同的特化提供不同的实现,则必须使用对类模板的委托(delegate):#include <iostream>
#include <ios>
template<auto ...Args>
struct calculate_impl {
static constexpr auto calc() { return (Args + ...); }
};
template<bool ...Args>
struct calculate_impl<Args...> {
static constexpr bool calc() { return (Args && ...); }
};
template<auto ...Args>
constexpr auto calculate() {
return calculate_impl<Args...>::calc();
}
int main() {
std::cout << calculate<1, 2, 3>(); // 6
std::cout << std::boolalpha
<< "\n" << calculate<false,true>() // false
<< "\n" << calculate<true, true>(); // true
}
关于c++ - 如何对 C++ 可变参数模板进行递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64877112/