gpt4 book ai didi

c++ - 在 GNU C++ 和 MSVC 问题之间的模板差异上调用 typeid

转载 作者:行者123 更新时间:2023-12-03 23:40:55 24 4
gpt4 key购买 nike

我正在尝试移植一个可以在 Linux (GCC/C++) 和 Windows (MSVC) 上运行和编译的代码
但是下面这行给我带来了麻烦

template <class TDerived>
struct Event
{
inline static std::string eventId = typeid(TDerived).name();
};

struct Derived : public Event<Derived>
{
Derived() = default;

};

代码使用 typeidname()设置事件名称,
在 GNU/C++ 中,它可以在 Linux 和 Apple (Clang) 中正确编译,甚至可以在使用 MingW 的 Windows 中正确编译。
但在使用 MSVC 的 Windows 中
它给出了以下错误
error C2027: use of undefined type 'Derived'
message : see declaration of 'Derived'
message : see reference to class template instantiation 'Event<Derived>' being compiled
主要是因为 Derived此时不完整,在 Event 中不可见范围。
但是为什么 GNU/GCC、MingW 和 Clang 编译成功呢?我们在 MSVC (Visual Studio) 中有解决方法吗?

最佳答案

C++标准说:

[expr.typeid]

When typeid is applied to a type-id ... If the type of the type-id is a class type or a reference to a class type, the class shall be completely-defined.


据我所知,该类并未在该上下文中完全定义。如果该解释是正确的,则违反了规则并且程序格式错误。也就是说,我不是 100% 确定,因为模板实例化使规则非常复杂。

But why does GNU/GCC, MingW and Clang succesfuly compiled it?


无论出于何种原因,它们的实现显然可以处理非完全定义的类。他们不需要成功编译它。从技术上讲,如果它们不提供诊断消息(假设对格式错误的程序的解释是正确的),则它们不符合标准。

Do we have a workaround in MSVC (Visual Studio)?


定义一个非内联静态成员似乎适用于 Godbolt:
template <class TDerived>
struct Event
{
static std::string eventId;
};

template <class TDerived>
std::string Event<TDerived>::eventId = typeid(TDerived).name();

请注意,该名称是实现定义的,并且不会在所有语言实现中都相同。

关于c++ - 在 GNU C++ 和 MSVC 问题之间的模板差异上调用 typeid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65935903/

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