我正在尝试编写一个可变参数模板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;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,error C2668: 'f': ambiguous call to overloaded function在尝试解析f<3,>()调用时,它不会编译报告错误消息.
我还尝试将我的递归基础案例更改为接受0模板参数而不是1:
template<>
constexpr int f()
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是这段代码也没有编译(消息error C2912: explicit specialization 'int f(void)' is not a specialization of a function template).
我可以提取第一个和第二个模板参数来进行编译和工作,如下所示:
template<int First, int Second, int... Rest>
constexpr int …Run Code Online (Sandbox Code Playgroud)