gpt4 book ai didi

c++ - "Typedef redefinition with different types"工作 MSVC 代码中的 Clang 错误

转载 作者:太空宇宙 更新时间:2023-11-04 12:04:41 29 4
gpt4 key购买 nike

我得到了一些在 MSVC 上编译良好的代码,我正试图让它在 Xcode 中的 Clang 上编译。我目前遇到一个问题,即使用以下 typedef 重新定义一个类:

typedef std::map<MyNS::istring, EntityState> Entity;

查看预处理后的输出,我可以看到在这个 typedef 之前有两个 class Entity 的前向声明。但是,class Entity 的实际定义不在预处理输出中,但它与新的 Entity 映射位于相同的命名空间中(虽然不是 MyNS...)。是导致此错误的前向声明吗?有没有什么方法可以使它在 MSVC 中有效,并且由于 Clang 的学究气而无法正常工作?

编辑:我手边没有 MSVC,但这里有一个片段,我放在一起来演示我遇到的错误类型(我已经简化了定义,以便它都适合一个小空间)。这会导致与我尝试使用 Clang 编译它时遇到的错误相同的错误。这在 MSVC 中有效吗?

namespace TheNS {

class Entity;

struct EntityState
{
std::string aString, anotherString;
int anInt;

EntityState() {}

EntityState(std::string a, std::string b, int i)
{
// constructor
}
};

typedef std::map<std::string, EntityState> Entity;

class Entity
{
public:
void SomeFunction();

private:
int m_aVar;

};

}

最佳答案

是的,这是不正确的。永远不应该编译,如果它在 MSVC 上编译——可能是编译器的一个错误。前向声明告诉编译器,TheNS::Entity 将是类而不是其他任何东西(不是枚举、 union 或 typedef)。确实,您的代码与

class Entity;   
typedef int Entity;

当然是不对的。

n3337 9.1/2

A declaration consisting solely of class-key identifier; is either a redeclaration of the namein the current scope or a forward declaration of the identifier as a class name. It introduces the class nameinto the current scope.

所以,在这之后

class Entity;

编译知道,Entity 将用作类名。这个名称可以重新声明为函数(在相同的范围内),在这种情况下你应该使用 class Entity,当你想使用 Entity 类(或重新声明 实体 name by typedef as says in comments).

7.1.3/6

In a given scope, a typedef specifier shall not be used to redefine the name of any type declared in thatscope to refer to a different type. [ Example:

class complex { /∗ ... ∗/ };
typedef int complex; // error: redifinition

— end example ]

关于c++ - "Typedef redefinition with different types"工作 MSVC 代码中的 Clang 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12687890/

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