37 lines
1.2 KiB
C++
37 lines
1.2 KiB
C++
#pragma once
|
|
#include <optional>
|
|
#include <utility>
|
|
|
|
namespace vl::mixin {
|
|
template<class Ret>
|
|
struct CallbackInfoReturnable;
|
|
// Base callback info: allows cancellation of original behavior.
|
|
struct CallbackInfo {
|
|
void cancel() noexcept { cancelled_ = true; }
|
|
bool isCancelled() const noexcept { return cancelled_; }
|
|
private:
|
|
bool cancelled_ = false;
|
|
template<class Ret>
|
|
friend class CallbackInfoReturnable;
|
|
};
|
|
|
|
// Returnable variant: holds an optional return value.
|
|
template<class Ret>
|
|
struct CallbackInfoReturnable : CallbackInfo {
|
|
template<class T>
|
|
void setReturnValue(T&& v) {
|
|
value_ = static_cast<Ret>(std::forward<T>(v));
|
|
this->cancel(); // setting a value implies skipping original unless user calls uncancel()
|
|
}
|
|
bool hasReturnValue() const noexcept { return value_.has_value(); }
|
|
const Ret& getReturnValue() const { return *value_; }
|
|
Ret& getReturnValue() { return *value_; }
|
|
void clearReturnValue() { value_.reset(); }
|
|
void uncancel() { if (!value_) /*no explicit value*/ cancelled_ = false; }
|
|
private:
|
|
using CallbackInfo::cancelled_;
|
|
std::optional<Ret> value_;
|
|
};
|
|
|
|
} // namespace vl::mixin
|