具有递归控制的可变模板



我需要一个模板函数来检查第一个值是否在后面的值中


我想我会尝试这样做,但它不起作用

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开始,您可以使用折叠表达式编写此函数,这比使用基本情况编写递归函数更简单。

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

请注意,您正在使用完全相同的参数递归地调用函数模板。这意味着你将无限递归,永远不会到达基本情况。

您可以通过命名第二个参数并将其余参数作为参数包来修复此问题。

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...);
}

这是一个演示

最新更新