Home > Back-end >  typeid result in different compilers
typeid result in different compilers

Time:11-12

I am watching the following video

It is mentioned here that g will report an error for the following code:

#include<vector>
#include<typeinfo>
#include<iostream>
struct S
{
    std::vector<std::string> b ;
};
int main()
{
    S s;
    std::cout << typeid(S::b).name();
}
error: invalid use of non-static data member ‘S::b’

But I did not encounter this kind of error under msvc and clang. Who is right and why? And why is it changed to

typeid(&S::b).name();

Is the result correct afterwards?

CodePudding user response:

Gcc is wrong (Bug 68604). S::b is an id-expression referring to a non-static data member, which could be used only in unevaluated context. Gcc seems failing in taking this as unevaluated expression.

As the workaround you could:

std::cout << typeid(decltype(S::b)).name();

Note that in typeid(&S::b).name();, &S::b gives a pointer to member; the result is different with using S::b.

  • Related