gpt4 book ai didi

c++ - 所以我不能 dynamic_cast< functionPointer >( ((void*)(myFuncPtr)) )?我应该怎么办?

转载 作者:行者123 更新时间:2023-11-28 08:21:55 26 4
gpt4 key购买 nike

我有一个基类 Parameter 和两个派生类:Scalar 和 Vector。在每个派生类中,我都有一个成员函数,它将函数指针作为输入:

在标量类中:

typedef double (*samplerType)(RandNum& rnState);
void RegisterSampler( samplerType input );

在 Vector 类中:

typedef std::vector<double> (*samplerType)(RandNum& rnState);
void RegisterSampler( samplerType input );

注意不同的返回类型:doublestd::vector<double> .我想在相互基类 Parameter 中定义此函数——所以我将函数更改为采用 (void* input)然后在 Scalar & Vector 类中定义函数时尝试了以下方法:

samplerType inputSampler = dynamic_cast< samplerType >(input);

但是,我在 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...);
}

关于c++ - 所以我不能 dynamic_cast< functionPointer >( ((void*)(myFuncPtr)) )?我应该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5520111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com