[[nodiscard]] 在 std::function 返回类型定义中?

Ali*_*ini 7 c++ std c++17

我想知道是否有办法拥有这样的东西:

using CallbackType = std::function<[[nodiscard]]bool(void)>; 
Run Code Online (Sandbox Code Playgroud)

(我知道上面的代码不会被编译并抱怨nodiscard不能应用于类型!)

我的目标是强制回调的调用者检查它的返回值!

Yam*_*ari 2

你可以做这样的事情

#include <iostream>
#include <utility>

template <typename R, typename... Args>
struct Function {
  using Fn = R (*)(Args...);

  Fn fn;

  explicit Function(Fn fn) : fn{fn} {}

  [[nodiscard]] R operator()(Args... args) {
    return (*fn)(std::forward<Args>(args)...);
  }
};

template <typename R, typename... Args>
Function(R (*)(Args...)) -> Function<R, Args...>;


bool bar(const int& x) { return x % 2 == 0; }

int main() {
  Function{&bar}(10);
}
Run Code Online (Sandbox Code Playgroud)

警告:

Compiler stderr

<source>: In function 'int main()':

<source>:24:17: warning: ignoring return value of 'R Function<R, Args>::operator()(Args ...) [with R = bool; Args = {const int&}]', declared with attribute 'nodiscard' [-Wunused-result]

   24 |   Function{&bar}(10);

      |   ~~~~~~~~~~~~~~^~~~

<source>:12:19: note: declared here

   12 |   [[nodiscard]] R operator()(Args... args) {

      |                   ^~~~~~~~
Run Code Online (Sandbox Code Playgroud)

编辑:扩展到成员函数 (+const) + lambda (带有推导指南)

Compiler stderr

<source>: In function 'int main()':

<source>:24:17: warning: ignoring return value of 'R Function<R, Args>::operator()(Args ...) [with R = bool; Args = {const int&}]', declared with attribute 'nodiscard' [-Wunused-result]

   24 |   Function{&bar}(10);

      |   ~~~~~~~~~~~~~~^~~~

<source>:12:19: note: declared here

   12 |   [[nodiscard]] R operator()(Args... args) {

      |                   ^~~~~~~~
Run Code Online (Sandbox Code Playgroud)