Smart pointer and covariance
stackoverflow How can I use covariant return types with smart pointers?
Alternatively, you can use the visitor pattern or something like my Dynamic Double Dispatch technique to pass a callback in to the returned object which can then invoke the callback with the correct type.
NOTE:
1、double dispatch,github CppCodeReviewers/Covariant-Return-Types-and-Smart-Pointers 中就是采用的这种思路
两篇文章给出的解决方案总结
1、github CppCodeReviewers/Covariant-Return-Types-and-Smart-Pointers
2、fluentcpp How to Return a Smart Pointer AND Use Covariance
上述两篇中,给出了实现方案,下面对它们的实现进行对比。
相同点
下面总结了两种实现方式的一些共性
1、下面两篇都使用virtual constructor来作为例子进行说明
2、都使用了CRTP
3、virtual clone implementation都没有public,都是因为使用了"raw pointer weak strong exception ownership transfer",因此不将其public能够在一定程度上环节,并且virtual clone implementation都使用了C++原生的pointer covariance
4、都涉及构建class hierarchy(build class hierarchy)
5、都涉及multiple polymorphic
6、都在derived classic中声明base,类似如下:
// desirable, but impossible in C++17
// see: http://cplusplus.github.io/EWG/ewg-active.html#102
// using typename... Bases::Bases;
不同点
下面是一些差异:
1、github CppCodeReviewers/Covariant-Return-Types-and-Smart-Pointers
a、它所构建的class hierarchy是相对比较简单的
b、它提供了consistent interface: cloneable
type
c、double dispatch/polymorphism,相对比较简单
2、fluentcpp How to Return a Smart Pointer AND Use Covariance
a、它的实现比较复杂,其复杂点在于build class hierarchy
TODO
1、arne-mertz.de Covariance with Smart Pointers