Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate mangled name of C++ template function

Tags:

c++

c++11

Let's say I have a C++ template function.

template <class T>
int foo(T& t) {
...
}

How can I calculate programmatically (not by using nm) the mangled name of a function?

Note, I am not interested in demangling. I am already familiar with the cxxabi header file that does the demangling.

like image 902
user855 Avatar asked Oct 19 '22 09:10

user855


1 Answers

It's possible to do it with typeid; the trick is to encode a pointer to the function into a type name by creating a type with a non-type template parameter whose value is the function pointer. For example:

template <class T> int foo(T&);
template <class U, U> struct IntegralConstant {};
std::cout << typeid(IntegralConstant<decltype(&foo<int>), &foo<int>>).name() << '\n';

This outputs 16IntegralConstantIPFiRiEXadL_Z3fooIiEiRT_EEE, which when piped through c++filt -t gives IntegralConstant<int (*)(int&), &(int foo<int>(int&))>. The tricky bit is to isolate the symbol _Z3fooIiEiRT_ (demangling to int foo<int>(int&)) from the full type name; this can be done by comparing the mangled type name to the equivalent when nullptr is passed in place of the function pointer:

template <class U, U> struct IntegralConstant {};
template <class U, U* u> std::string mangledSymbolName() {
    std::string null = typeid(IntegralConstant<U*, nullptr>).name();
    std::string symbol = typeid(IntegralConstant<U*, u>).name();
    return symbol.substr(null.size() - 3, symbol.size() - null.size() + 0);
}

Example: http://melpon.org/wandbox/permlink/6b46CBOv0ZwIMukk

The magic constants 3 and 0 are dependent on the encodings in the C++ ABI of nullptr, pointers to external symbols, and class templates; they'll also require adjustment if IntegralConstant is placed in a namespace.

like image 155
ecatmur Avatar answered Oct 22 '22 00:10

ecatmur