typeid operator in C++

心不动则不痛 提交于 2021-02-08 19:49:15

问题


I have the following code

int main()
{
    cout << "Please enter your name..." << endl;
    cin >> name;
    cout << "Data type = " << typeid(name).name() << endl;
    cin.get();
    return 0;
}

According to the various textbooks and pieces of documentation I've read about the typeid operator, I should expect to read

"Data type = string"

as the output. Instead, I get the following

class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >

Does anyone have any idea where I'm going wrong? FWIW, I'm using Visual Studio 2010 Professional.


回答1:


Nothing is wrong.

Those text books, first of all, should have told you the result of name() is implementation-defined, and could very well be "". Secondly, that type is std::string. The std::string type is just a typedef of std::basic_string with char and friends.




回答2:


std::string is an alias for the char specialization of the std::basic_string class template. That mouthful you see output is the full typename including all template parameters.



来源:https://stackoverflow.com/questions/3721078/typeid-operator-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!