获取静态类功能的类类型
Get the class type of a static class function
我有一个函数指针指向静态类功能Foo::bar()
,并希望获得类的类型(Foo
)。现在,我知道如果bar
是Foo
的成员函数,而不是静态函数,则可以获得类型,而具有以下类型特征:
template<class T> struct class_of;
template<class T, class R> struct class_of<R T::*> { using type = T; };
但是,这对静态功能不起作用。我想做的是以下内容: class_of<Foo::bar>::type
== Foo
在我看来,编译器知道所有相关信息,那么如何完成?
裸函数指向静态成员函数的指针是同一类型的作为非成员函数的函数指针。
也许您可以在功能指针周围使用包装器来包含类信息:
#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;
}
相关文章:
- 错误:在尝试检测 std::cout 是否<< t 时,功能强制转换为数组类型;有效
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- C++从成员类型中扣除类型的功能模板?
- 这种错误的原因是什么:将"功能"重新定义为不同类型的符号
- 模板功能:根据类型名称进行转换
- 如何在同一个模板功能上专门化几种类型?
- 错误:未知类型名称"功能跟踪"
- 我对C 中共享指针列表进行排序的功能未完成类型
- 共享_ptr中多功能数组的类型是什么
- 确定功能主体中的返回类型
- 返回类型不可知模板类成员功能
- 类型推论模板功能返回类型
- C 功能模板指定第二个模板参数类型
- 为什么指定数据类型而不是构造功能参数?C
- C 尝试使用模板输出功能来显示不同类型的数据
- 为什么BOOST :: HANA :: EXAREMIS ::键入实验功能?类型列表的棘手是什么
- 将多种类型传递给STD ::功能C
- C 中此功能的返回类型的含义
- C++ 使用包含不同类型功能对象的基和派生类的 Reactor
- 请求从非标量类型转换为非标量类型(功能)