是否有可能避免有关 void 函数返回值的外部引用换行错误

Is there a possibility to avoid the xrefwrap error about void function returning a value?

本文关键字:外部 引用 换行 错误 返回值 函数 能避免 void 是否      更新时间:2023-10-16

我有一个像std::vector<std::function<void()>> functions这样的向量定义,为了存储一个项目,我以这种方式使用一个函数:

template <typename Fun, typename Instance, typename ... Args>
void AddFunction(std::string name, Fun&& fun, Instance* instance, Args&& ... args)
{
  /*something is going on here*/
  functions.push_back(std::bind(fun, instance, std::forward<Args>(args)...));
  /*something is going on here*/
}

问题是有时传递给std::bind的函数可以返回某种值。我想过使用 lambdas,我尝试了这样的东西

template <typename Fun, typename Instance, typename ... Args>
void AddFunction(std::string name, Fun&& fun, Instance* instance, Args&& ... args)
{
  /*something is going on here*/
  auto lambda = [&]() -> void
  {
    fun(std::forward<Args>(args)...);
  };
  functions.push_back(std::move(lambda));
  /*something is going on here*/
}

但是每次我尝试使用AddFunction都会显示一条错误消息,说term does not evaluate to a function taking n arguments n是我传递给AddFunction的函数所接受的参数数。

是否有一些解决方法,以便即使存储的函数返回值,我也可以存储 std::function<void()> 类型的项目?

两者

functions.push_back(std::bind(fun, instance, std::forward<Args>(args)...));

  auto lambda = [&]() -> void
  {
    (instance->*fun)(std::forward<Args>(args)...);
  };
  functions.push_back(std::move(lambda));

与Visual Studio一起工作得很好。