Print the type of a parameter (ParmVarDecl) with clang API

谁都会走 提交于 2019-12-03 06:35:54

Got the answer to my question in the llvm irc:

There is a method std::string clang::QualType::getAsString(SplitQualType split)

So this does work for me:

ParmVarDecl* param = *someParameter;
cout << QualType::getAsString(param->getType().split()) << endl;

You can use typeid to get the name of any type. Although it will vary from compiler to compiler, and may not be a pretty name.

#include <iostream>
#include <typeinfo>

struct MyStruct { };

int main()
{
    std::cout << typeid(MyStruct).name() << std::endl;
}

If you need to do this for a lot of classes, you could make the call part of a base class, then any class that needs the functionality can just inherit from it.

#include <iostream>
#include <typeinfo>

class NamedClass
{
  public:
    virtual ~NamedClass() { }

    std::string getNameAsString()
    {
        return typeid(*this).name();
    }
};

class MyStruct : public NamedClass
{
};

int main()
{
    MyStruct ms;
    std::cout << ms.getNameAsString() << std::endl;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!