c++ - 如何在可能是任何类的属性的 void 函数上创建 typedef?

标签 c++ visual-studio oop vector typedef

当我们做的时候

typedef void FuncCharPtr(char*, int) ;
vector<FuncCharPtr*> FuncVec ;
void Add(FuncCharPtr* f)
{
    FuncVec.push_back(f);
}

我们不允许像 FuncCharPtr 这样的类型传递

 void (someClass::*)b(char*, int);
 void (someOtherClass::*)b(char*, int);

并且我们希望将来自两个类的函数的链接保持在同一个 vector 中,以便能够使用类似的东西同时调用所有订阅者

void CastData(char * data, int length){
    for(size_t i = 0 ; i < FuncVec.size(); i++){
        char* dataCopy = new char[length];
        memcpy(dataCopy, data, length);
        FuncVec[i](dataCopy, length);
                    delete[] dataCopy;
    }
}

如何解决这样的问题?

最佳答案

你不能为此使用函数指针。类类型是指向成员函数的指针类型的一部分,因此没有一种类型可以工作。

完成你想做的事情的最好方法是使用 the function classthe bind function来自 Boost、C++ TR1 或 C++0x。

您可以维护一个 std::vector<std::function<void(char*, int)> >并使用 bind函数将指向成员函数的指针绑定(bind)到您希望调用成员函数的类的实例:

struct A { void foo(int) { } };
struct B { void bar(int) { } };

typedef std::function<void(int)>   Function;
typedef std::vector<Function>      FunctionSequence;
typedef FunctionSequence::iterator FunctionIterator;

FunctionSequence funcs;

A a;
B b;

funcs.push_back(std::bind(&A::foo, &a, std::placeholders::_1));
funcs.push_back(std::bind(&B::bar, &b, std::placeholders::_1));

// this calls a.foo(42) then b.bar(42):
for (FunctionIterator it(funcs.begin()); it != funcs.end(); ++it)
    (*it)(42);

关于c++ - 如何在可能是任何类的属性的 void 函数上创建 typedef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4845504/

相关文章:

c++ - DUMPBIN 不显示所有功能

C++ - 为模板类专门化成员函数

C++ 类 - 每 N 毫秒递增和递减属性

c# - #if 调试 --> #if myOwnConfig?

java - 具有两个列表的类的组合和转发方法

c++ - 抽象类——C++实践中的隐藏实现

c++ - C++ 中的 LNK2005 和 LNK1169 错误

c++ - 为什么我不能在 main.cpp 中包含 C 文件?

git - Visual Studio 2017 Team Services : Can log into github account, 但无法推送更改

c# - 如何确定我在列表中引用的子类?