我正在尝试编写一个可变参数模板constexpr
计算给定模板参数总和的函数。这是我的代码:
template<int First, int... Rest>
constexpr int f()
{
return First + f<Rest...>();
}
template<int First>
constexpr int f()
{
return First;
}
int main()
{
f<1, 2, 3>();
return 0;
}
不幸的是,它不会编译并报告错误消息error C2668: 'f': ambiguous call to overloaded function
在试图解决的同时f<3,>()
call.
我还尝试更改我的递归基本情况以接受 0 个模板参数而不是 1 个:
template<>
constexpr int f()
{
return 0;
}
但这段代码也无法编译(消息error C2912: explicit specialization 'int f(void)' is not a specialization of a function template
).
我可以提取第一个和第二个模板参数来使其编译和工作,如下所示:
template<int First, int Second, int... Rest>
constexpr int f()
{
return First + f<Second, Rest...>();
}
但这似乎并不是最好的选择。那么,问题是:如何优雅地编写这个计算?
UP:我也尝试将其写为单个函数:
template<int First, int... Rest>
constexpr int f()
{
return sizeof...(Rest) == 0 ? First : (First + f<Rest...>());
}
这也行不通:error C2672: 'f': no matching overloaded function found
.