[英]Sequence of user-defined conversions in C++
I'm facing a problem with a sequence of user-defined conversions in C++. 我在C ++中遇到一系列用户定义的转换问题。 Consider the following code: 考虑以下代码:
struct A
{
A(int);
};
struct B
{
B(A);
};
struct C
{
C(B);
};
The constructors are defined somewhere. 构造函数在某处定义。 Now, the following statements work fine: 现在,以下语句可以正常工作:
A(1); // A <- int
B(1); // B <- A <- int
C(A(1)); // C <- B <- A <- int
C(B(1)); // C <- B <- A <- int
C(B(A(1))); // C <- B <- A <- int
However, when I try to compile the following: 但是,当我尝试编译以下内容时:
C(1); // C <- B <- A <- int
I get the following error: 我收到以下错误:
error: no matching function for call to ‘C::C(int)’
no known conversion for argument 1 from ‘int’ to ‘B’
I know that such a construction is illegal in C++. 我知道在C ++中这种构造是非法的。 Nevertheless, my question is: 不过,我的问题是:
C(B(A(1)))
are somewhat annoying. C(B(A(1)))
的构造有些令人讨厌。 For completeness, I found several related questions (eg, Why user-defined conversions are limited? ). 为了完整起见,我发现了几个相关的问题(例如, 为什么用户定义的转换受到限制? )。 However, none address my question. 但是,没有人解决我的问题。
As you've said, your first question is already answered. 如您所说,您的第一个问题已得到回答。
As for a work around, assuming you don't want to add an A constructor to your C class, you can just bank on the one allowed implicit conversion: 关于变通方法,假设您不想在C类中添加A构造函数,则可以依靠一个允许的隐式转换:
C(B(1));
The following should also works: 以下也应该起作用:
C(A(1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.