如何使typedef的void函数可以是任何类的属性? [英] How to make typedef on void function that could be property of any class?

查看:144
本文介绍了如何使typedef的void函数可以是任何类的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们做

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

我们不允许以FuncCharPtr类型传递

we do not allow to pass as FuncCharPtr types like

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

,我们想保持链接到同一向量中两个类的函数,

and we want to keep links to functions from both classes in same vector so to be able to call all subscribers at once WITH SOMETHING LIKE

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;
    }
}

如何解决这类问题?

推荐答案

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

You can't use a function pointer for this. The class type is a part of the type of a pointer to a member function, so there is no one type that would work.

最好的方式来完成你想要的要做的是使用 函数 类和 bind 函数从Boost,C ++ TR1或C ++ 0x。

The best way to accomplish what you want to do is to use the function class and the bind function from Boost, C++ TR1, or C++0x.

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

You can maintain a std::vector<std::function<void(char*, int)> > and use the bind function to bind pointers to member functions to the instance of the class on which you want the member function to be called:

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);

这篇关于如何使typedef的void函数可以是任何类的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆