C++:是否可以使用带有模板参数的动态绑定?

发布于 2024-11-06 02:29:24 字数 733 浏览 1 评论 0原文

我有一个模板函数,它接受函数对象(“函子”)作为模板参数:

 template <typename Func> int f (void) {
    Func func;
    return func ();
};

struct Functor {
   virtual int operator () (void) = 0;
};

struct Functor0 : Functor {
    int operator () (void) {
        return 0;
    }
};

struct Functor1 : Functor  {
    int operator ()  (void) {
        return 1;
    }
};

我想避免使用 if-else 块,例如:

int a;
if (someCondition) {
    a = f<Functor0> ();
}
else {
    a = f<Functor1> ();
}

有没有办法使用类似于动态绑定的方法,即类似:

a = f<Functor> (); // I know this line won't compile, it is just an example of what I need

并在运行时决定什么(派生)类型作为模板参数传递?

I have a template function which accepts a function-object ('functor') as a template parameter:

 template <typename Func> int f (void) {
    Func func;
    return func ();
};

struct Functor {
   virtual int operator () (void) = 0;
};

struct Functor0 : Functor {
    int operator () (void) {
        return 0;
    }
};

struct Functor1 : Functor  {
    int operator ()  (void) {
        return 1;
    }
};

I want to avoid an if-else block like:

int a;
if (someCondition) {
    a = f<Functor0> ();
}
else {
    a = f<Functor1> ();
}

Is there a way to use something similar to dynamic binding, i.e something like:

a = f<Functor> (); // I know this line won't compile, it is just an example of what I need

and decide in runtime what (derived) type is passed as the template parameter?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

咆哮 2024-11-13 02:29:24

有没有办法使用类似于动态绑定的东西

?这根本不可能。在代码中的某些时候,您需要区分大小写。当然,这并不需要手动编写;您可以使用宏(或模板)来生成必要的代码。但它必须存在。

Is there a way to use something similar to dynamic binding

No. This is fundamentally impossible. At some point in your code you need to have the case distinction. Of course, that doesn’t have to be written manually; you can use macros (or again templates) to generate the necessary code. But it needs to be there.

淡淡離愁欲言轉身 2024-11-13 02:29:24

避免检查的一种方法(如果这确实是您想要做的),是使用数组 - ..

Functor* fp[] = { new Functor0(), new Functor1() };

现在 - 使用 someCondition 作为索引。

a = (*fp[someCondition])();

这仅依赖于运行时多态性,而不是您正在使用的冗余模板机制...(顺便说一句,不要忘记清理!)

当然,这是令人讨厌且坦率地说是多余的, if< 的开销/code> 无关紧要,但它为代码添加的清晰度却很重要......

One way to avoid the check (if that is REALLY what you want to do), is to use an array - ..

Functor* fp[] = { new Functor0(), new Functor1() };

now - use someCondition as an index.

a = (*fp[someCondition])();

this relies simply on run-time polymorphism rather than the redundant template mechanism you are using... (btw. don't forget to cleanup!)

Of course, this is nasty and frankly redundant, the overhead of the if will be insignificant, but the clarity it adds to the code is significant...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文