我正尝试编写一个可变参数模板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;
}
很不幸,尝试解析f<3,>()
时出现错误信息error C2668: 'f': ambiguous call to overloaded function
。
我还尝试将递归的基本情况更改为接受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...>();
}
但这似乎不是最好的选择。因此,问题是:如何以优雅的方式编写这个计算?
更新:我也尝试将其编写为单个函数:
template<int First, int... Rest>
constexpr int f()
{
return sizeof...(Rest) == 0 ? First : (First + f<Rest...>());
}
而且这也不起作用:错误 C2672:未找到匹配的重载函数“f”
。
constexpr int f(int a, ...)
? - exampleRest...
的长度(类似于转换为另一个基数),这不能作为constexpr
评估。 - alexeykuzmin0