相互依赖的constexpr构造函数
我有两个类,每个类都可以彼此构造。
示例:
class B;
class A{
public:
double val;
constexpr A(B b): val(b.val){};
};
class B{
public:
double val;
constexpr B(A a): val(a.val){};
};
我需要转发declare b
类,所以一个知道它。当这些构造函数不是constexpr
时,我可以将它们的定义移至源文件中,并愉快地编译。
但是,要使它成为constexpr,必须在标题中定义它们。 b
可以从a
构造,因为它看到了a
的完整定义。 a
无法从b
构造,因为它只会看到声明,因此对b :: val
一无所知。
我只剩下类B
constexpr
。是否有两种课程的方法?
I have two classes, each constructible from the other.
Example:
class B;
class A{
public:
double val;
constexpr A(B b): val(b.val){};
};
class B{
public:
double val;
constexpr B(A a): val(a.val){};
};
I need to forward-declare class B
, so A knows about it. When these constructors are not constexpr
, I can move their definitions to a source file and it happily compiles.
However, to make it constexpr, they have to be defined in the header. B
is ok to construct from A
, because it sees the full definition of A
. A
cannot construct from B
because it only sees a declaration, and therefore has no idea about B::val
.
I'm left with only making class B
constexpr
. Is there a way to do it for both classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用GCC我会得到错误( https://godbolt.org/z/qvp7absdr
)失败是因为类型
b
在使用时是不完整的,这是构造函数a :: a(b b)
的定义。为了处理此问题,我们可以等到我们声明
b
才能完全定义构造函数并使用B。从本质上讲,将构造函数的定义移出类a
课堂后b
请参阅没有汇编问题的示例:
https://godbolt.org/z/4444fbcr8sh
Using gcc I get the error (https://godbolt.org/z/qvP7absdr):
So this fails because type
B
is incomplete when it is used it is the definition of the constructorA::A(B b)
.In order to deal with this we can wait until we have declared
B
fully before we define the constructor and use B. Essentially, move the definition of the constructor out of classA
and after classB
See an example without compilations issues:
https://godbolt.org/z/44fbcr8sh