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

问题描述

我正在尝试移植一个可以在 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]

当 typeid 应用于 type-id ... 如果 type-id 的类型是类类型或对类类型的引用,则该类应该是完全定义的。

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

但为什么 GNU/GCC、MingW 和 Clang 编译成功?

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

我们在 MSVC (Visual Studio) 中有解决方法吗?

定义一个非内联静态成员似乎适用于 Godbolt:

template <class TDerived>
struct Event
{
    static std::string eventId;
};

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

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

,

我找到了一个变通方法并且它有效。

template <class TDerived>
struct Event
{
private:
    static std::string getEventId() { return typeid(TDerived).name(); }

public:
    inline static std::string eventId = getEventId();
};

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...