a c*_*zen 5 c++ templates function-pointers
我不是高级程序员.该问题的简短版本是:如何为全局函数创建一个模板,该函数调用指向仅在运行时已知的类的成员函数的指针(以及具有不同类型的参数的人)?
该函数是全局函数,其声明如下:
template<class T>
const double gExtFunc(const double &x, \
const double &y, \
const double &ep, \
const double &es, \
// function pointer here
const double &a, \
const double &k, \
double &mid_OUT, \
short &i_OUT, \
double &eps_OUT, \
short &trip_OUT);
Run Code Online (Sandbox Code Playgroud)
这在some(virtual public)类中调用.例如(不使用ellipsis):
class DerivedA: virtual public Base
{
public:
void funcA(...)
{
// ...
m_varA = gExtFunc(...);
// ...
}
// ...
const double commonFunc(const double &a, const double &k) const;
};
const double DerivedA::commonFunc(const double &a, const double &k) const
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
该Base班只是为公共变量居多.指向函数的指针指向commonFunc()所有虚拟类中的相同名称,但每个虚拟类中的参数的定义和类型不同.例如,上面DerivedA使用它有两个const double&参数,而a DerivedE用:
const double DerivedE::commonFunc(const int &n, const double &k) const;
Run Code Online (Sandbox Code Playgroud)
现在,我设法使用lambda函数(基于此,当我只有一个m_varA),这意味着函数指针参数gExtFunc()是这样的:
const double gExtFunc(..., std::function<const double(const double&, const double&)> fPnt, ...)
Run Code Online (Sandbox Code Playgroud)
它被称为,例如.在里面DerivedA,如:
m_varA = gExtFunc(..., [this](const double &a, const double &k){ return commonFunc(a, k); }, ...)
Run Code Online (Sandbox Code Playgroud)
它起作用了,但只要它只在一个类中被调用.一旦我尝试调用它DerivedE,因为m_varE它也失败了:was not declared in this scope指向它的定义m_varE.
我已经看到了这个答案,但这需要我先创建一个我不能做的对象.所以我试着绕过它并将指针替换为函数参数,如下所示:
template<class T> // first the template, above the function
const double gExtFunc(..., T *t, const double(T::*t)(const double&, const double&) fPnt, ...)
Run Code Online (Sandbox Code Playgroud)
并且,在定义中:t->fPnt(...).但怎么gExtFunc()称呼?我试过这个:
m_varA = gExtFunc(..., new DerivedA(), &DerivedA::commonFunc, ...)
Run Code Online (Sandbox Code Playgroud)
但它失败了,was not declared in this scope和上面一样.我被困在这里.如果有替代我想做的事情,我非常愿意改变它.
编辑:
作为一个临时的,丑陋的解决方案,我将其复制gExtFunc()到需要它,修剪和调整的每个类,包括放弃指向函数的指针,只是直接调用成员函数commonFunc().目前只有3个案例,但未来可能会带来更多,这就是为什么我认为这个问题很丑陋以及为什么这个问题仍然有效.
如果我的答案有误,请随意投反对票。我只是想帮忙。我没有足够的能力阅读所有这些内容并理解你的确切问题,但我想我理解你问题的基础。我假设您正在做一些事情,例如创建一个参数可以变化的函数,例如:
template <typename T> func(T arg1){}
Run Code Online (Sandbox Code Playgroud)
在代码中的其他地方,您希望它T是一个int或一个或其他任何东西,但您在转换为正确的类型时char *遇到了麻烦。T
我要做的就是在记忆中工作。我的功能是这样的
enum types {
OBJECT,
INT,
STRING
};
int type;
int addrOfType;
void func(int addr, int typ) {
type = typ;
addrOfType = typ;
}
Run Code Online (Sandbox Code Playgroud)
并调用它做类似的事情
object argument;
func((int)&argument,OBJECT);
Run Code Online (Sandbox Code Playgroud)
以及您正在检索数据的代码中的其他位置
switch (type) {
case OBJECT:
object obj = *(object*)addrOfType;
//do whatever with obj
break;
}
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助。这看起来是一个棘手的问题,所以我想当我坐在这里无聊时,我会尝试尝试提供帮助。如果我的回答很糟糕,请随意否定。在手机上发帖太难了。