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?

Dan D.
  • 73,243
  • 15
  • 104
  • 123
Baris Akar
  • 4,895
  • 1
  • 26
  • 54

2 Answers2

26

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;
Baris Akar
  • 4,895
  • 1
  • 26
  • 54
-5

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;
}
Node
  • 3,443
  • 16
  • 18
  • 5
    How this is connected to the question asked? The q. was about clang API, he wanted to do this on the clang AST. – Anton Korobeynikov Jul 13 '11 at 09: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 Jul 13 '11 at 17:23