强制派生类重写至少一个虚函数

强制派生类重写至少一个虚函数

本文介绍了强制派生类重写至少一个虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下这个简单的基类:

Imagine this simple base class:

struct simple_http_service
{
  virtual reply http_get(…);
  virtual reply http_post(…);
  virtual reply http_delete(…);
  // etc.
};

我想阻止用户派生此类而不覆盖其中至少一个,并防止他们实例化simple_http_service

I'd like to prevent the user from deriving from this class without overriding at least one of these and prevent them from instantiang simple_http_service

有什么 nice 方法可以做到这一点吗?

Is there some nice way to do this?

推荐答案

这听起来像是一个很奇怪的约束.一定要保护用户免受不正确的使用,但不要试图禁止您只是看不见重点"的事情.如果从类中派生而不覆盖这三个函数中的任何一个都没有意义,那么让用户覆盖他喜欢的尽可能多或少的函数,并相信他不会做无意义的不覆盖派生的事情任何功能.这样做对用户没有害处,只是不是很有用.

That sounds like a really odd constraint. By all means protect the user from incorrect usage, but don't try to prohibit things that you just "can't see the point of". If there's no point in deriving from your class without overriding any of the three functions, then let the user override as many or as few function as he likes, and trust that he won't do the pointless thing of deriving without overriding any of the functions. There's no harm in the user doing that, it's just not very useful.

但是,如果您需要执行此操作(再次,我建议您重新考虑),则不要使用虚函数.而是传递函数指针或函数对象(或std::function/boost::function)回调.使基类看起来像这样:

But if you do need to enforce this (again, I'd suggest you rethink), then don't use virtual functions. Instead, pass function pointers or function objects (or std::function/boost::function) callbacks. Make the base class look something like this:

struct simple_http_service
{
  typedef std::function<reply (...)> func_type;
  reply http_get(...) { return get_func(...); }
  reply http_post(...) { return post_func(...); }
  reply http_delete(...) { return delete_func(...); }
  // etc.

private:
  func_type get_func;
  func_type post_func;
  func_type delete_func;
};

现在,只需添加必要的构造函数(或自由/静态函数,以便您可以对其进行命名以避免歧义),以便仅在至少提供了一个函数对象时才能实例化该类.

Now just add the necessary constructors (or free/static functions so you can name them to avoid ambiguity) so that the class can only be instantiated when at least one of the function objects are supplied.

这篇关于强制派生类重写至少一个虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:32