[英]So I can't dynamic_cast< functionPointer >( ((void*)(myFuncPtr)) )? What should I do?
我有一个基类,参数和两个派生类:标量和向量。 在每个派生类中,我都有一个成员函数,该成员函数将函数指针作为输入:
在标量类中:
typedef double (*samplerType)(RandNum& rnState);
void RegisterSampler( samplerType input );
在Vector类中:
typedef std::vector<double> (*samplerType)(RandNum& rnState);
void RegisterSampler( samplerType input );
注意不同的返回类型: double
和std::vector<double>
。 我想在共同基类Parameter中定义此函数-因此我将函数更改为采用(void* input)
,然后在定义Scalar&Vector类中的函数时尝试了以下操作:
samplerType inputSampler = dynamic_cast <samplerType>(输入);
但是,在VS 2005中出现以下错误:
error C2680: 'double (__cdecl *)(RandNum &)' : invalid target type for dynamic_cast
target type must be a pointer or reference to a defined class
Grumble Grumble Grumble ...我不确定这是否是有效的(标准允许)C ++,但是我想无论哪种方式我都会将其视为设计中的缺陷。
因此 ,我的标准方法是使用函数的返回类型对基类进行模板化,但我做不到。 根据设计,基类Parameter必须不包含所有类型信息。 设计继承有其他方法吗?
我对Google所做的尝试实际上几乎没有实现函数指针-因此,我相信这实际上是无效的语法 ,但也许仅仅是一个真正非常罕见的设计挑战? 这是救援的函子吗?
除了James指出的设计缺陷外,确实不能从函数指针转换为普通的void*
指针。 但是,您可以在任意类型(自由到自由,成员到成员)的函数指针之间进行转换:
typedef void (*samplerType)();
// in base class ...
samplerType sampler_;
template<class F>
void RegisterSampler(F sampler){
// template so the user doesn't have to do the type cast
sampler_ = reinterpret_cast<samplerType>(sampler);
}
// in derived class, where you access the sampler, you need to cast it back:
// (scalar)
typedef double (*realSamplerType)(RandNum& rnState);
// made-up function ...
void UseSampler(){
realSamplerType sampler = reinterpret_cast<realSamplerType>(sampler_);
double ret = sampler(param...);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.