Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeid result in different compilers

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?

like image 735
Kargath Avatar asked May 18 '26 12:05

Kargath


1 Answers

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.

like image 133
songyuanyao Avatar answered May 21 '26 02:05

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!