没有公共继承的类之间的链式转换 [英] Chained conversion between classes without public inheritances
问题描述
问题
我有一系列大约10个模板类A,B,C,D ......
I have a series of ~10 template classes A, B, C, D, ...
我想启用从一个类到系列中以前的类的转换:
I want to enable conversions from a class to previous classes in the series:
- D-> C,B或A
- C-> B或A
- B-> A
如何在不使用公共继承的情况下实现这一目标?
How to make that happen without using public inheritance?
测试1 (公共继承)
- 我不想继承公共方法.
测试2 (定义1 + 2 + ... n个转换运算符):
Test 2 (define 1 + 2 + ... n conversion operators):
- 为第n个模板类定义n个转换运算符 模板类.
- 非常乏味
- Define n conversion operators for the nth template class template class.
- Very tedious
测试3 (每个班级1个转换运算符):
Test 3 (1 conversion operator per class):
- 仅允许从下一级别的类型转换为该级别的类型.
例如,它允许从D转换为C,但不能从D转换为B.
For example, that enables conversion from D to C, but not from D to B.
Test(也在 godbolt.org ):
template <typename Convertible>
class A {
public:
operator Convertible() { return Convertible(); }
};
using B = A<int>;
using C = A<B>;
using D = A<C>;
int main() {
D d;
auto b = B(d);
return 0;
}
编译错误:
error: no matching function for call to ‘A<int>::A(D&)’
auto b = B(d);
^
实际用例
A,B,C,D ...是由对象S的一层创建的每个节点(代理).
A, B, C, D ... are each nodes (proxies) created by a layer of an object S.
-
类型1层定义图节点的内存组织 (指针/数组).
Type 1 layers define memory organization of nodes of a graph (pointer/array).
类型2图层将图层转换为另一个容器. (例如,带有哈希的层,用于通过键为节点建立索引并跟踪节点的交换.)
Type 2 layers convert a layer to another container. (e.g. layer with a hash for indexing nodes by keys and tracking swapping of nodes.)
用户可以通过多种方式堆叠图层以创建对象S.
User can stack the layers in many ways to create the object S.
我希望将一层的节点转换为上一层的节点.
I want nodes of one layer to convert to nodes of previous layers.
这是可能的,因为指向节点内容的指针/索引将是相同的.
This is possible because the pointer to/index of the content of the nodes would be the same.
推荐答案
尽管@hlt的方法可以满足您的要求,但又不了解更多上下文,但是我对在A
中实现转换持谨慎态度.在我能想到的情况下,A
不应意识到B
,C
或D
,所以我建议使用其他实现.
Although @hlt's approach will do what you ask, without knowing more about the context, I'm wary about implementing the conversion in A
. In the cases I can think of, A
shouldn't be aware of B
, C
or D
, so I'll suggest a different implementation.
您可以创建测试3的变体,在其中每个类实现一个转换运算符,但是在其中您还继承了模板化的间接转换运算符,如下所示:
You can create a variant of your test 3, where you implement one conversion operator per class, but where you also inherit a templated indirect conversion operator, like so:
#include <type_traits>
template <typename T1, typename T2>
struct indirect_conversion {
template <typename T, typename = std::enable_if_t<std::is_constructible_v<T, T2>>>
operator T() {
return static_cast<T1 *>(this)->operator T2();
}
};
struct A {};
struct B : indirect_conversion<B, A> {
operator A();
};
struct C : indirect_conversion<C, B> {
operator B();
};
struct D : indirect_conversion<D, C> {
operator C();
};
A a = D();
这篇关于没有公共继承的类之间的链式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!