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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With