[英]variadic template with recursive control
我需要一個模板 function 來檢查第一個值是否在后面的值中。
我以為我會嘗試這樣的事情,但它不起作用
template<class T, class U>
bool is_in_set(const T &t, const U &u) {
return t == u;
}
template<class T, class ...Args>
bool is_in_set(const T &t, Args...args) {
return false || is_in_set(t, args...);
}
它可以編譯,但我收到以下警告warning C4717: 'is_in_set': recursive on all control paths, function will cause runtime stack overflow
誰能幫我修復它並解釋為什么它不起作用?
從 C++17 開始,您可以使用fold-expression編寫此 function,這比使用基本情況編寫遞歸 function 更簡單。
template<class T, class ...Args>
bool is_in_set(T const & t, Args const & ...args)
{
return (... || (t == args));
}
現在你可以這樣稱呼它。
is_in_set(1, 2, 3, 4); // false
is_in_set(1, 2, 1, 4); // true
這是一個演示
考慮到您的代碼,您會收到警告,因為您在此行有無限遞歸:
return false || is_in_set(t, args...); // infinite recursion here
請注意,您使用完全相同的 arguments 遞歸調用 function 模板。 這意味着您將無限遞歸,並且永遠不會達到基本情況。
您可以通過命名第二個參數並將剩余的 arguments 作為參數包來解決此問題。
template<class T, class U>
bool is_in_set(T const & t, U const &u)
{
return t == u;
}
template<class T, class U, class ...Args>
bool is_in_set(T const & t, U const & u, Args const &...args)
{
return is_in_set(t, u) || is_in_set(t, args...);
}
這是一個演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.