you can do something like this
#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);
}
Warning:
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) {
| ^~~~~~~~
EDIT:
Extend to member function (+const) + lambda ( with deduction guide )
template <typename T, typename = std::void_t<>>
struct Function;
template <typename R, typename... Args>
struct Function<R (*)(Args...)> {
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 T, typename R, typename... Args>
struct Function<R (T::*)(Args...)> {
using MFn = R (T::*)(Args...);
T* t;
MFn mfn;
Function(T* t, MFn mfn) : t{t}, mfn{mfn} {}
[[nodiscard]] R operator()(Args... args) {
return (t->*mfn)(std::forward<Args>(args)...);
}
};
template <typename T, typename R, typename... Args>
struct Function<R (T::*)(Args...) const> {
using MFn = R (T::*)(Args...) const;
const T* t;
MFn mfn;
Function(const T* t, MFn mfn) : t{t}, mfn{mfn} {}
[[nodiscard]] R operator()(Args... args) {
return (t->*mfn)(std::forward<Args>(args)...);
}
};
template <typename T>
struct Function<T, std::void_t<decltype(&T::operator())>> final
: Function<decltype(&T::operator())> {
explicit Function(const T& t)
: Function<decltype(&T::operator())>(&t, &T::operator()) {}
};
template<typename T>
Function(T) -> Function<T>;
template<typename T, typename R, typename ...Args>
Function(T*, R(T::*)(Args...)) -> Function<R(T::*)(Args...)>;
template<typename T, typename R, typename ...Args>
Function(const T*, R(T::*)(Args...) const) -> Function<R(T::*)(Args...) const>;
void foo() {}
struct Foo
{
void foo() const {}
};
int main() {
Function{&foo}();
Function{[]{}}();
Foo foo{};
Function{&foo, &Foo::foo}();
}