问题描述
我正在尝试移植一个可以在 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;
};
在 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();
};