network-experiment/bmrshared/include/bmrshared/function_wrapper.hpp

61 lines
2.0 KiB
C++

// GNU Lesser General Public License v3.0
// Copyright (c) 2023 Bart Beumer <bart@4beumer.nl>
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License v3.0 as published by
// the Free Software Foundation.
//
#pragma once
#include "flexible_value.hpp"
#include "invoke.hpp"
#include <array>
#include <functional>
#include <string>
#include <type_traits>
namespace bmrshared
{
class IDataSource;
template<typename T, typename... TExtraArguments>
struct function_wrapper;
template<typename T, typename... TExtraArguments>
requires(std::is_const<T>::value == true)
struct function_wrapper<T, TExtraArguments...>
{
using wrapper_type = std::function<flexible_value(const T&, const IDataSource&, TExtraArguments...)>;
template<typename M, typename... TSourceParams>
static wrapper_type Wrap(M T::* callableFn, TSourceParams... paramNames)
{
std::array<std::string, sizeof...(TSourceParams)> names{paramNames...};
return [callableFn, names](const T& obj, const IDataSource& source, TExtraArguments... args)
{
return invoke<M, T, sizeof...(TSourceParams), TExtraArguments...>(obj, callableFn, names, source, args...);
};
}
};
template<typename T, typename... TExtraArguments>
requires(std::is_const<T>::value == false)
struct function_wrapper<T, TExtraArguments...>
{
using wrapper_type = std::function<flexible_value(T&, const IDataSource&, TExtraArguments...)>;
template<typename M, typename... TSourceParams>
static wrapper_type Wrap(M T::* callableFn, TSourceParams... paramNames)
{
std::array<std::string, sizeof...(TSourceParams)> names{paramNames...};
return [callableFn, names](T& obj, const IDataSource& source, TExtraArguments... args)
{
return invoke<M, T, sizeof...(TSourceParams), TExtraArguments...>(obj, callableFn, names, source, args...);
};
}
};
} // namespace bmrshared