模板类的模板函数指针- c++
Template function pointer of template class - C++
template<typename C, typename Arg>
int foo(C* c, int (C::*func)(Arg), Arg a)
{
c->*func(a);
}
要调用'foo',我们必须同时传递A*和&A::bar,
foo(A*,&A::bar,var);
是否有一种方法来定义模板(例如作为一个结构体),这样就不需要传递"a *"?我如何定义一个模板,从"& a::bar"得到a * ?
如果你想在该实例上调用非静态方法,你不能避免传递该实例,除非你不介意在临时的、默认构造的实例上调用它:
template<typename C, typename Arg>
int call_on_temp(int (C::*func)(Arg), Arg a)
{
C temp;
temp.*func(a);
}
或者调用者显式地将实例绑定到一个函子:
template<typename F, typename Arg>
int call_on_functor(F func, Arg a)
{
func(a);
}
使调用站点变得丑陋:
call_on_functor(std::bind(std::mem_fn(&Class::method), instance), arg);
(你仍然需要实例,你只是把它从一个地方移动到另一个地方)。
注意,你可以从函数指针推断出A的类型,但你不能推断出一个实例来调用你的函数。如果您想调用静态方法,则根本不需要类类型:template<typename Arg>
int call_on_static(int (*func)(Arg), Arg a)
{
func(a);
}
这个应该做你需要的事情:
template<typename unused>
struct member_function_pointer_type_helper;
template<typename R, typename C>
struct member_function_pointer_type_helper<R C::*> {
typedef C type;
};
template<typename F>
struct member_function_pointer_type : member_function_pointer_type_helper<typename std::remove_cv<F>::type> {
};
的例子:
struct A { void foo() { ... } };
typedef member_function_pointer_type<decltype(&A::foo)>::type a_type; // 'A'
a_type my_a;
my_a.foo();
这是通过为成员函数提供专门的模板,然后简单地导出该成员函数的类部分来实现的。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错