这种间接函数调用的优点是什么? [英] What's the advantage of this indirect function call?

查看:165
本文介绍了这种间接函数调用的优点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Bar {
public:
bool foo(int i){
return foo_(i);
}
private:
virtual bool foo_(int i)= 0;
};

现在我想知道:为什么要使用这种间接方式?有没有什么理由可以说明上述会比简单的选择更好:

  class Bar {
public:
virtual bool foo(int i)= 0;
};


解决方案

这是非虚拟接口习语(NVI)。 Herb Sutter的那一页有很多关于它的细节。然而,在C ++ FAQ Lite所说的内容中,你会发现你所阅读的内容此处此处

NVI的主要优点是界面与实施分离。一个基类可以实现一个通用算法并将其呈现给世界,而其子类可以通过虚拟函数实现该算法的细节。外部用户可以屏蔽算法细节的变化,特别是如果您稍后决定要添加前处理和后处理代码。



明显的缺点是您必须编写额外的代码。另外, private 虚函数让很多人感到困惑。许多编码员错误地认为你不能覆盖他们。 Herb Sutter似乎喜欢 private virtuals,但是恕我直言,在实践中更加有效地遵循C ++ FAQ Lite的建议并使它们成为 protected


I found the following code in a library:

class Bar {
public:
  bool foo(int i) {
   return foo_(i);
  }
private:
  virtual bool foo_(int i) = 0;
};

Now I'm wondering: Why would you use this indirection? Could there be any reasons why the above would be better than the simple alternative:

class Bar {
public:
  virtual bool foo(int i) = 0;
};

解决方案

This is the Non-Virtual Interface Idiom (NVI). That page by Herb Sutter has a good bit of detail about it. However, temper what you read there with what the C++ FAQ Lite says here and here.

The primary advantage of NVI is separating interface from implementation. A base class can implement a generic algorithm and present it to the world while its subclasses can implement the details of the algorithm through virtual functions. Outside users are shielded from changes in the algorithm details, especially if you later decide you want to do add pre- and post-processing code.

The obvious disadvantage is that you have to write extra code. Also, private virtual functions are confusing to a lot of people. Many coders mistakenly think you can't override them. Herb Sutter seems to like private virtuals, but IMHO it's more effective in practice to follow the C++ FAQ Lite's recommendation and make them protected.

这篇关于这种间接函数调用的优点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆