【问题标题】:C++: Is it possible to use dynamic binding with a template parameter?C++:是否可以使用带有模板参数的动态绑定?
【发布时间】:2011-05-09 11:36:11
【问题描述】:

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

 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

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

【问题讨论】:

  • 我不明白为什么这里需要模板 - 这不只是运行时多态性的一个简单示例吗?
  • 你可以避免if / elsea = someCondition ? f&lt;Functor0&gt;() : f&lt;Functor1&gt;();
  • @unapersson - 这是一个很好的问题 - 我正在尝试清理一些现有的代码,而我的问题只是在这样做时突然出现在我的脑海中 - 我相信它可以通过使用多态来解决,但无论如何我都想知道答案。 @Chris Lutz - 这只是 if/else 的另一种语法,不是吗?

标签: c++ templates inheritance


【解决方案1】:

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

没有。这基本上是不可能的。在您的代码中的某个时刻,您需要区分大小写。当然,这不必手动编写;您可以使用宏(或再次使用模板)来生成必要的代码。但它必须在那里。

【讨论】:

    【解决方案2】:

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

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

    现在 - 使用 someCondition 作为索引。

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

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

    当然,这很讨厌而且坦率地说是多余的,if 的开销将是微不足道的,但它为代码增加的清晰度却很重要......

    【讨论】:

    • 如果 OP 会生成 operator() const 或使用一些智能指针 (boost::scoped_ptr / std::unique_ptr),则可以使用 Functor const&amp; fp[] 避免清理。
    • @Matthieu M,当然,我只是想强调这种方法,并指出采用if 方法很可能更好——纯粹是因为它更容易理解! :)
    猜你喜欢
    • 2017-05-25
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多