I have a function pointer to a static class function Foo::bar(), and want to get the type of the class (Foo). Now, I know that I could get the class type if bar were a member function of Foo, instead of a static function, with something like the following type trait:
template<class T> struct class_of;
template<class T, class R> struct class_of<R T::*> { using type = T; };
However, this doesn't work for static functions. What I'd like to do is the following:
class_of<Foo::bar>::type == Foo
It seems to me that the compiler knows all relevant information, so how can this be done?
A bare function pointer to a static member function is of the same type as a function pointer to a non-member function.
Maybe you can use a wrapper around your function pointer to include the class information:
#include <iostream>
struct Foo {
template<class Arg>
static void bar(Arg arg) {
std::cout << "called with " << arg << std::endl;
}
};
template<class T, class Ret, class... Args>
struct Wrapper {
using F = Ret(*)(Args...);
F f_;
constexpr Wrapper(F f) noexcept : f_{f} {}
template<class... RealArgs>
constexpr Ret operator()(RealArgs&&... args) const {
return f_(std::forward<RealArgs>(args)...);
}
};
template<class T, class Ret, class... Args>
constexpr Wrapper<T, Ret, Args...> make_wrapper(Ret(*f)(Args...)) {
return Wrapper<T, Ret, Args...>(f);
}
template<class T>
void inspect(const T&) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
int main() {
constexpr auto foobar_int = make_wrapper<Foo>(Foo::bar<int>);
inspect(foobar_int);
foobar_int(4);
constexpr auto foobar_double = make_wrapper<Foo>(Foo::bar<double>);
inspect(foobar_double);
foobar_double(3.8);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With