Does the C++ standards define a utility for wrapping a function in a type (as distinct from wrapping it in a value)?
After Googling a bunch of names that seem related, I'm not finding anything, but then again, I know of a few things where I'd never guess the name.
Edit:
- I already know how to get a type that can dynamically take on the value of a function (either
std::function
or a good old function pointers likeint(*f)(int)
) but that specifically excludes from the type the one thing I most want to include: the actual function to be called. - I already know how to get the type of a function from its name (
decltype(fn)
) which is not what I want, for the same reasons as listed above.
I find myself needing to make a type where its operator()
exactly matches a function foo
(in my case, a C function from a 3rd part library). Ideally, the type should inline away to nothing any time it's used. As a one off, this is easy:
struct foo_t {
ret_t operator()(SomeType t, int i) {
return foo(t, i);
}
};
However, there is at least one cases where this is a thing that needs to be done to a bunch of different functions: deleters for std::unique_ptr<T,D>
while interfacing with opaque handles (e.g. from C libraries):
std::unique_ptr<FILE*, fclose_t> f(fopen(n, "r"));
std::unique_ptr<obj*, free_t> o((obj*)malloc(sizeof(obj)));
...
Rather than define fclose_t
, free_t
, etc. myself, what I'd like to do is something like this:
std::unique_ptr<FILE*, type_fn<fclose>> f(fopen(n, "r"));
std::unique_ptr<obj*, type_fn<free>> o((obj*)malloc(sizeof(obj)));
...
And that isn't even that hard... if you are happy to define type_fn
yourself:
template<auto *f> struct fn_type {
template<class... A>
auto operator() (A&&... a) {
return f(std::forward<A>(a)...);
}
};
Which brings me back to the opening question: does C++ define something like that?