使用C++ 11 中的模板类型的成员函数指针创建方法参数
Create method argument with member function pointer from template types in C++ 11
我想实现以下目标:
template <typename F>
class MyTemplate {
public:
void SomeMethod(F f) {
//...
}
template <typename C, typename O>
void SomeMethod(C::*F f, O& o) { // this does not work, I want a member function pointer here
//...
}
};
static void StaticFunction(int);
class SomeClass {
public:
void MemberMethod(int);
};
MyTemplate<void(int)> mt;
mt.SomeMethod(StaticFunction);
SomeClass SomeClassInstance;
mt.SomeMethod(&SomeClass::MemberMethod, SomeClassInstance); // I want to call it like this
我想创建一个带有函数类型参数的模板。模板应为 C 样式或静态函数指针以及成员函数"创建"重载。如何从应该用于声明模板实例的自由函数类型创建成员函数类型?
我希望能够将模板与以下类型一起使用:
- 空
- (空)
- 空(整型)
- int(void) int
- (int) int
- (int, int, int, int)
- void(int, int, int, int)
- 等。
以下是dyp提供的答案:
template <typename F>
class MyTemplate {
public:
void SomeMethod(F f) {
//...
}
template <typename C, typename O>
void SomeMethod(F C::* f, O& o) { // this does work
//...
}
};
static void StaticFunction(int) {}
struct SomeClass {
public:
void MemberMethod(int) {}
};
int main()
{
MyTemplate<void(int)> mt;
mt.SomeMethod(StaticFunction);
SomeClass SomeClassInstance;
mt.SomeMethod(&SomeClass::MemberMethod, SomeClassInstance); // I want to call it like this
}
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址