c++ - 在 C++ 11 中使用来自模板类型的成员函数指针创建方法参数

标签 c++ templates function-pointers pointer-to-member

我想实现以下目标:

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(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++ 11 中使用来自模板类型的成员函数指针创建方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28954542/

相关文章:

c - GCC C 认为我将函数声明为静态的?

在结构上调用 free 会引发运行时错误

c++ - 为什么我不能将模板参数传递给另一个模板?

c++ - 删除时会调用模板参数的模板类的析构函数吗?

c# - 在 System::Collections::Generic::List<T> 类型的列表中列出是可能的吗?

c++ - 将字符串从一个 .cpp 文件传输到另一个

javascript - 在 javascript 中使用 handlebars 模板变量

c - c语言中函数指针的正确使用方法

c++ - 模板的内联关键字

python clang : Getting Template Arguments