使用模板功能设计层次结构类 [英] Designing hiearchical classes with template function

查看:68
本文介绍了使用模板功能设计层次结构类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个类Base,该类的成员函数带有模板参数:

I am writing a class Base which has a member function taking a template parameter:

class Base {
  template<class T>
  void func(const T& t) { ... }
};

有一个类Derived从概念上继承了Base的性质,并且具有相同的功能func,但实现方式不同.

There's a class Derived which conceptually inherits natures of Base and has the same function func with different implementation.

起初,我想到从Base派生Derived并将其虚拟化,但是我不能,因为它是模板.

At first I thought of deriving Derived from Base and make func virtual, but I can't because it's template.

我也想到了CRTP,但这是一个选择,因为实例必须能够放入容器中并且可以在不知道实例确切类型的情况下进行访问:

I also thought of CRTP, but it's an option because instances must be able to put into a container and be accessible without knowing exact types of them:

std::vector<Base*> v = ...;
v[0]->func(...);
v[1]->func(...);

T可能类型的重载也不是可选的.

Overloading for possible types of T is also not an option.

针对这种情况的最佳解决方案是什么?

What is the best solution to this situation?

除了该主题之外,您还会推荐针对此类问题的参考资料(最好是书籍)吗?

And aside from the topic, would you recommend references (preferably books) for such kind of problems?

推荐答案

使用C ++很难做到这一点.它与所谓的一流多态"有关,这意味着如果C ++中的值可以具有多态类型,这将很容易.情况并非如此.

This is not something easily done with C++. It's related to something called "first class polymorphism", which means it would be easy if the values in C++ could have polymorphic types. This is not the case.

如果您可以使用通用解决方案(这意味着所有T的代码f必须相同),则可以执行此操作,但这将是一项艰巨的任务.

If you'll be fine with a generic solution (that means the code f must be the same for all T), you can maybe do it, but it will be a laborious task.

基本上,您将想要用一个不是通用类型的参数替换您的const T &t参数,但该参数会从所有可能类型的t中捕获f所需的所有行为

Basically, you'll want to replace your const T &t parameter with a parameter whose type that wouldn't be generic, but will capture "inside" all the behaviour f needs from ts of all possible types.

举个例子,假设T是一个函子,f用一个int参数调用.在这种情况下,您将声明更改为

For an example, let's say T is meant to be a functor, that f calls with an int argument. In this case, you'll change the declaration to

  virtual void func(const std::function<void(int)>& t) { ... }

和虚拟功能将开始起作用.但是,这意味着T的接口必须在开始在派生类中实现之前被固定(这意味着,如果您改变主意并想使用类型为ostream的参数调用t,则真不走运.)

and virtual functions will start to work. However, that means the interface of Ts will have to be fixed before you start to implement it in derived classes (meaning if you change your mind and want to call t with an argument of type ostream, you're out of luck).

但是,创建此类多态包装很容易( boost::any boost::function ),甚至难以解决( any_iterator ).这完全取决于您要做什么.

However, creating such polymorphic wrappers ranges from easy (as is boost::any, boost::function) to hard or even impossible (any_iterator). It's very dependent on what you want to do.

这篇关于使用模板功能设计层次结构类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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