将由 boost::variant 聚合的类型的对象传递给接受该 boost::variant 的函数
假设我有:
class TypeA { };
class TypeB { };
typedef boost::variant<TypeA, TypeB> Type;
这没问题:
void foo(Type t) { }; int main(){ A型a; foo(a); }
这不能编译:
void foo(Type &t) { }; int main(){ A型a; foo(a); }
错误:
<块引用>“Type&”类型引用的初始化无效从 “TypeA”类型的表达式
这也无法编译:
void foo(Type *t) { }; int main(){ A型a; foo(&a); }
错误:
<块引用>无法将参数“1”转换为“TypeA*”为“Type*”为“void” foo(类型*)'
有没有办法通过引用(如情况 2)或指针将 boost::variant 聚合的类型之一的实例传递给接受 boost::variant 的函数(如情况3)?
非常感谢!
Suppose I have:
class TypeA { };
class TypeB { };
typedef boost::variant<TypeA, TypeB> Type;
This is ok:
void foo(Type t) { }; int main(){ TypeA a; foo(a); }
This does not compile:
void foo(Type &t) { }; int main(){ TypeA a; foo(a); }
with the error:
invalid initialization of reference of type ‘Type&’ from
expression of type ‘TypeA’Also this does not compile:
void foo(Type *t) { }; int main(){ TypeA a; foo(&a); }
with the error:
cannot convert ‘TypeA*’ to ‘Type*’ for argument ‘1’ to ‘void
foo(Type*)’
Is there a way to pass to a function that accepts a boost::variant an instance of one of the types aggregated by that boost::variant, either through a reference (as in case 2) or a pointer (as in case 3)?
Thank you very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
1 中真正发生的情况:
2 或 3 中不会发生的情况:
您有两种解决方案(对于非模板 foo):
Type
,然后获取对此的指针/引用,boost::variant
用于隐式转换以启动第三种解决方案是更改 foo 本身,并将其设为模板。这取决于你想做什么。
What really happens in 1:
What cannot happen in 2 or 3:
You have two solutions (for a non template foo):
Type
, then take a pointer/reference to thisboost::variant<TypeA*,TypeB*>
for implicit conversion to kick inA third solution is to change foo itself, and make it template. It depends on what you want to do.
聚合意味着
boost::variant
包含TypeA
和TypeB
。事实并非如此。它包含TypeA
或TypeB
。它更像是一个联合而不是一个结构。您可以按值传递
TypeA
,因为存在从TypeA
到Type
的隐式转换。没有从
TypeA&
到Type&
(或TypeA*
到Type*
)的隐式转换,并且不应该有不会的。想象一下,如果将对TypeA
对象的引用传递给foo()
并且foo()
决定将其替换为代码>TypeB
值。在不知道
foo()
和TypeA
/TypeB
是什么的情况下,我无法给您更具体的建议,但也许您可以使用函数模板。即或重载函数:
Aggregation implies that the
boost::variant
contains bothTypeA
andTypeB
. It doesn't. It contains eitherTypeA
orTypeB
. It's more like a union than a struct.You can pass
TypeA
by value because there is an implicit conversion fromTypeA
toType
.There is no implicit conversion from
TypeA&
toType&
(orTypeA*
toType*
) and there shouldn't be. Think of what would happen if a reference to aTypeA
object was passed intofoo()
andfoo()
decides to replace it with aTypeB
value.Without knowing what
foo()
andTypeA
/TypeB
are, I can't give you more specific advice but perhaps you can use a function template. i.e.or overloaded functions: