gpt4 book ai didi

c++ - 专用结构/类中未识别的数据成员

转载 作者:行者123 更新时间:2023-11-30 03:19:41 25 4
gpt4 key购买 nike

为了包含条件数据成员,我使用专门的模板而不是 namespace ,然后在每个专门化中重载赋值运算符。发生的事情是在编译期间,特化的成员变量不被识别。我不明白为什么,在互联网上也找不到任何东西。

enum Def : int {A, B};

template<Def T>
struct X {};

// Forward declaration does not help, like it would in non-template implementations.
/*
* template<>
* struct X<B>;
*/

template<>
struct X<A>
{
int a;
int b;
X<A> & operator = (const X<B> & obj)
{
a = obj.a;
b = obj.b;
}
}

template<>
struct X<B>
{
int a;
int b;
int c;
int d;
X<B> & operator = (const X<A> & obj)
{
a = obj.a;
b = obj.b;
}
}

现在发生的事情是,在编译时,我得到了 X<B> 的错误没有名为 a 的成员和 b .这里有什么问题?

最佳答案

问题是,当X<B>在特化的定义中实例化 X<A> ,(这是 X<A>::operator = 的定义所要求的,)特化的定义 X<B>还不可见。这意味着它将是 implicitly instantiated来自没有成员 a 的主模板和 b .

您可以移动 X<A>::operator = 的定义超出特化的定义X<A>并在 X<B> 的特化定义之后.例如

template<>
class X<A>
{
int a;
int b;
X<A> & operator = (const X<B> & obj);
};

template<>
class X<B>
{
...
};

X<A> & X<A>::operator = (const X<B> & obj)
{
a = obj.a;
b = obj.b;
}

关于c++ - 专用结构/类中未识别的数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53459705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com