【问题标题】:A function pointer that points to a function that takes an object of a template class with said function pointer as template argument. Possible?一个函数指针,它指向一个函数,该函数接受一个模板类的对象,该函数指针作为模板参数。可能的?
【发布时间】:2009-07-04 16:45:32
【问题描述】:

x__x

我想做这样的事情:

typedef long (* fp)(BaseWindow< fp > & wnd, HWND hwnd, long wparam, long lparam);

但我得到一个编译错误:

错误 C2065:“fp”:未声明 标识符

有可能以某种方式实现吗?

【问题讨论】:

  • 请粘贴编译器报错的那一行。
  • 哎呀。指针被命名为 fp_t,但在输入时它没有出现在帖子的预览中,所以我将其更改为 fp,但忘记修改错误消息。

标签: c++ templates function-pointers typedef


【解决方案1】:

不,它不是,因为模板参数的类型会包含它自己。这将导致类型中的无限递归。

如果你接受它的基类而不是类模板特化,那是很有可能的

struct TemplateBase {

};

typedef long (*fpType)(TemplateBase&, HWND, long, long);

template<fpType FP>
struct BaseWindow : TemplateBase {

};


long sampleFunc(TemplateBase &b, HWND hwnd, long wparam, long lparam) {
  ...
}

int main() {
    BaseWindow<sampleFunc> bw;
    sampleFunc(bw, ...);
}

你想用这个做什么?

【讨论】:

  • 对于我面临的问题,这是一个疯狂的想法。但也许有更好的方法。在这里以评论的形式解释这个问题太长了,所以也许我稍后会提出一个正式的问题。谢谢你的回答。
  • 请注意,您可以将虚函数添加到基类中,并且从 sampleFunc 中调用它们会将控制权交给派生类,就像在非模板类中使用虚函数一样。
【解决方案2】:

【讨论】:

    猜你喜欢
    • 2021-10-28
    • 2020-01-12
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 2013-04-30
    相关资源
    最近更新 更多