Path: blob/main/contrib/llvm-project/compiler-rt/lib/orc/unique_function.h
213766 views
//===----- unique_function.h - moveable type-erasing function ---*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// unique_function works like std::function, but supports move-only callable9/// objects.10///11/// TODO: Use LLVM's unique_function (llvm/include/llvm/ADT/FunctionExtras.h),12/// which uses some extra inline storage to avoid heap allocations for13/// small objects. Using LLVM's unique_function will require first14/// porting some other utilities like PointerIntPair, PointerUnion, and15/// PointerLikeTypeTraits. (These are likely to be independently useful16/// in the orc runtime, so porting will have additional benefits).17///18//===----------------------------------------------------------------------===//1920#ifndef ORC_RT_UNIQUE_FUNCTION_H21#define ORC_RT_UNIQUE_FUNCTION_H2223#include <memory>2425namespace orc_rt {2627namespace unique_function_detail {2829template <typename RetT, typename... ArgTs> class Callable {30public:31virtual ~Callable() = default;32virtual RetT call(ArgTs &&...Args) = 0;33};3435template <typename CallableT, typename RetT, typename... ArgTs>36class CallableImpl : public Callable<RetT, ArgTs...> {37public:38CallableImpl(CallableT &&Callable) : Callable(std::move(Callable)) {}39RetT call(ArgTs &&...Args) override {40return Callable(std::forward<ArgTs>(Args)...);41}4243private:44CallableT Callable;45};4647} // namespace unique_function_detail4849template <typename FnT> class unique_function;5051template <typename RetT, typename... ArgTs>52class unique_function<RetT(ArgTs...)> {53public:54unique_function() = default;55unique_function(std::nullptr_t) {}56unique_function(unique_function &&) = default;57unique_function(const unique_function &&) = delete;58unique_function &operator=(unique_function &&) = default;59unique_function &operator=(const unique_function &&) = delete;6061template <typename CallableT>62unique_function(CallableT &&Callable)63: C(std::make_unique<64unique_function_detail::CallableImpl<CallableT, RetT, ArgTs...>>(65std::forward<CallableT>(Callable))) {}6667RetT operator()(ArgTs... Params) {68return C->call(std::forward<ArgTs>(Params)...);69}7071explicit operator bool() const { return !!C; }7273private:74std::unique_ptr<unique_function_detail::Callable<RetT, ArgTs...>> C;75};7677} // namespace orc_rt7879#endif // ORC_RT_UNIQUE_FUNCTION_H808182