Share via

using typeid with template differs in behaviour for MSVC against GNU C++, Clang and even MingW

cebuhax0r 66 Reputation points
2021-01-28T11:18:17.087+00:00

Ive got a code that looks like this

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

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

};

This compiles correctly in GNU C++, Apple Clang and even MingW in Windows).
But in windows using Visual Studio compiler (MSVC) I am getting the following error

error C2027: use of undefined type 'Derived'
message : see declaration of 'Derived'
message : see reference to class template instantiation 'Event<Derived>' being compiled

I understand that Derived is incomplete at the scope of Event, but why does other compiler can succesfuly recognize it?
Is there any workaround for it to work on VS C++?

my environment
Visual Studio Community 2019
The CXX compiler identification is MSVC 19.28.29336.0

Please help, this kind of line is rampant on what I am porting right now and changing them will be a huge effort.

Reported to Microsoft:
https://developercommunity2.visualstudio.com/t/typeid-with-template-differs-in-behaviou/1323822

Developer technologies | C++
Developer technologies | C++

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.


Answer accepted by question author

  1. Viorel 126.9K Reputation points
    2021-01-28T11:49:01.717+00:00

    Try this workaround:

    template <class TDerived>
    struct Event
    {
    private:
        static std::string getEventId( ) { return typeid( TDerived ).name( ); }
    
    public:
        inline static std::string eventId = getEventId();
    };
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.