問題描述
我正在嘗試編寫一個可變參數(shù)模板 constexpr
函數(shù)來計算給定模板參數(shù)的總和.這是我的代碼:
I'm trying to write a variadic template constexpr
function which calculates sum of the template parameters given. Here's my code:
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重載函數(shù)> 打電話.
Unfortunately, it does not compile reporting an error message error C2668: 'f': ambiguous call to overloaded function
while trying to resolve f<3,>()
call.
我還嘗試將遞歸基本情況更改為接受 0 個模板參數(shù)而不是 1 個:
I also tried to change my recursion base case to accept 0 template arguments instead of 1:
template<>
constexpr int f()
{
return 0;
}
但此代碼也無法編譯(消息 error C2912: explicit specialization 'int f(void)' is not a specialization of a function template
).
But this code also does not compile (message error C2912: explicit specialization 'int f(void)' is not a specialization of a function template
).
我可以提取第一個和第二個模板參數(shù)來編譯和工作,就像這樣:
I could extract first and second template arguments to make this compile and work, like this:
template<int First, int Second, int... Rest>
constexpr int f()
{
return First + f<Second, Rest...>();
}
但這似乎不是最好的選擇.那么,問題是:如何以優(yōu)雅的方式編寫此計算?
But this does not seem to be the best option. So, the question is: how to write this calculation in an elegant way?
UP:我也試著把它寫成一個單一的函數(shù):
UP: I also tried to write this as a single function:
template<int First, int... Rest>
constexpr int f()
{
return sizeof...(Rest) == 0 ? First : (First + f<Rest...>());
}
這也不起作用:error C2672:'f':找不到匹配的重載函數(shù)
.
推薦答案
您的基本情況是錯誤的.您需要一個空列表的案例,但正如編譯器所建議的那樣,您的第二次嘗試不是有效的模板專業(yè)化.為零參數(shù)定義有效實例化的一種方法是創(chuàng)建一個接受空列表的重載
Your base case was wrong. You need a case for the empty list, but as the compiler suggests, your second try was not a valid template specialization. One way to define a valid instantiation for zero arguments is to create an overload that accepts an empty list
template<class none = void>
constexpr int f()
{
return 0;
}
template<int First, int... Rest>
constexpr int f()
{
return First + f<Rest...>();
}
int main()
{
f<1, 2, 3>();
return 0;
}
<小時>
為了完整起見,也是我的第一個答案,@alexeykuzmin0 通過添加條件來修復(fù):
for completeness sake also my first answer, that @alexeykuzmin0 fixed by adding the conditional:
template<int First=0, int... Rest>
constexpr int f()
{
return sizeof...(Rest)==0 ? First : First + f<Rest...>();
}
這篇關(guān)于如何編寫可變參數(shù)模板遞歸函數(shù)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!