13

I need to print the type of a parameter in a C++ source file using the clang API.

If I have a parameter representation in clang (ParmVarDecl* param) I can print the name of the parameter using param->getNameAsString(). I would need a method param->getTypeAsString(), but there is no such method. So is there another way to do this task?

2 Answers 2

27

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;
3
  • 2
    You probably just saved me a week
    – Steven Lu
    Commented May 12, 2015 at 18:00
  • 1
    You certainly saved me the entire night. Commented Jun 18, 2016 at 22:47
  • 3
    You need to add a clang::PrintingPolicy nowadays. Such that the call now looks like: QualType::getAsString(param->getType().split(), PrintingPolicy{ {} })
    – erikzenker
    Commented Sep 3, 2018 at 21:57
-7

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;
}
2
  • 5
    How this is connected to the question asked? The q. was about clang API, he wanted to do this on the clang AST. Commented Jul 13, 2011 at 9:40
  • Like Anton wrote, I want to do this with the clang API, so that when I process a source file, I can print functions and their parameter types. But I'll try your answer, maybe I can get use of it.
    – Baris Akar
    Commented Jul 13, 2011 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.