【发布时间】:2015-07-23 14:31:39
【问题描述】:
我有 2 节课:
enum class Enumtype
{
typ1,
typ2,
};
class A
{
private:
retType Func1(arg1Type, arg2Type, arg3Type);
retType Func2(arg1Type, arg2Type, arg3Type);
public:
A();
retType Func(Enumtype, arg1Type, arg2Type, arg3Type);
}
class B
{
private:
arg1Type a;
arg2Type b;
arg3Type c;
public:
int FunctionFromB(Enumtype);
}
所以主要用途是这样的:
int B::FunctionFromB(Enumtype x)
{
A* objectA;
for(int i=0; i<whatever; i++)
{
objectA->Func(x, a+i, b+(2*i), c+(3*i));
}
}
retType A::Func(Enumtype x, arg1type a, arg2type b, arg3type c)
{
switch(x)
{
case Enumtype::typ1:
return Func1(a, b, c);
case Enumtype::typ2:
return Func2(a, b, c);
default:
return Func1(a, b, c);
}
}
不幸的是,我不想在每个循环中都运行 switch,所以我想到了这个:
- 在 A 类写“朋友 B 类”
- 删除 A::Func()
- 在 B::FunctionFromB() 中创建函数 ptr
- 在 B::FunctionFromB() 中进行切换,将上述函数 ptr 初始化为 A::Func1 或 A::Func2。 Switch 类似于 A::Func() 中的那个
- 不是运行 objectA->Func(x, a, b, c),而是运行 objectA->functionPtr(a, b, c)
如何做到这一点?我尝试使用 std::function 执行此操作,但我不知道如何正确声明/初始化/调用它以使其工作。
编辑:
我已经编辑了 FunctionFromB,因为我跳过了一个重要部分 -> Func 在循环中调用了不同的参数。
EDIT2:
提供了帮助,我回答说如何使用 C 风格的函数 ptr 执行此操作,但我想让它与 std::function 一起使用。我是这样做的(注意 B 类和枚举是一样的):
class A
{
private:
retType Func1(arg1Type, arg2Type, arg3Type);
retType Func2(arg1Type, arg2Type, arg3Type);
public:
A();
typedef std::function<retType(arg1Type, arg2Type, arg3Type)> funcPtr;
}
int B::FunctionFromB(Enumtype typeB)
{
A* objectA;
A::funcPtr func = nullptr;
switch(type)
{
case Enumtype::typ2:
func = std::bind(&A::Func2, objectA, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3);
break;
case Enumtype::typ2:
default:
func = std::bind(&A::Func1, objectA, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3);
break;
}
for(int i=0; i<whatever; i++)
func(a+i, b+(2*i), c+(3*i));
}
我猜,它有效。如果有人在这里发现错误或更好的方法,请告诉我;)
【问题讨论】:
-
您想了解指向成员函数的指针,例如here.
标签: c++ function class pointers friend