File: Functional.h

package info (click to toggle)
dolphin-emu 2512%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 76,328 kB
  • sloc: cpp: 499,023; ansic: 119,674; python: 6,547; sh: 2,338; makefile: 1,093; asm: 726; pascal: 257; javascript: 183; perl: 97; objc: 75; xml: 30
file content (68 lines) | stat: -rw-r--r-- 1,728 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright 2025 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <concepts>
#include <functional>
#include <memory>
#include <type_traits>

// TODO C++23: Replace with std::move_only_function.

namespace Common
{

template <typename T>
class MoveOnlyFunction;

template <typename R, typename... Args>
class MoveOnlyFunction<R(Args...)>
{
public:
  using result_type = R;

  MoveOnlyFunction() = default;

  template <std::invocable<Args...> F>
  requires(!std::same_as<std::decay_t<F>, MoveOnlyFunction>)
  MoveOnlyFunction(F&& f) : m_ptr{std::make_unique<Func<F>>(std::forward<F>(f))}
  {
  }

  result_type operator()(Args... args) const { return m_ptr->Invoke(std::forward<Args>(args)...); }
  explicit operator bool() const { return m_ptr != nullptr; }
  void swap(MoveOnlyFunction& other) { m_ptr.swap(other.m_ptr); }

private:
  struct FuncBase
  {
    virtual ~FuncBase() = default;
    virtual result_type Invoke(Args...) = 0;
  };

  template <typename F>
  struct Func : FuncBase
  {
    explicit Func(F&& f) : func{std::forward<F>(f)} {}
    result_type Invoke(Args... args) override { return func(std::forward<Args>(args)...); }
    std::decay_t<F> func;
  };

  std::unique_ptr<FuncBase> m_ptr;
};

// A functor type with an invocable non-type template parameter.
// e.g. Providing a function pointer will create a functor type that invokes said function.
// It allows using function pointers in contexts that expect a type, e.g. as a "deleter".
template <auto Invocable>
struct InvokerOf
{
  template <typename... Args>
  constexpr auto operator()(Args... args) const
  {
    return std::invoke(Invocable, std::forward<Args>(args)...);
  }
};

}  // namespace Common