Reputation: 73
I have a function wrapper class im trying to work on.
I want to be able to show the name of the function that is passed into the template.
template<auto Func>
struct FuncWrapper final {
FuncWrapper() {
StrFuncName = typeid(Func).name();
std::cout << StrFuncName << std::endl;
}
template<typename... Args>
auto operator()(Args&&... args) const { }
std::string StrFuncName;
};
void Function() { }
FuncWrapper<Function> wrapper;
Upvotes: 1
Views: 126
Reputation: 39818
It is possible to implement a version of this portably using typeid
:
template<auto&>
struct symbol;
template<auto &S>
const char* name() {return typeid(symbol<S>).name();}
The name is of course *implementation-defined; in practice, it may or may not require demangling (in addition to stripping the symbol<…>
decoration).
There is the alternative approach of using commonplace compiler extensions:
template<auto &S>
const char* name() {return __PRETTY_FUNCTION__;}
This too has to have the const char * name<…>()
stripped.
Getting a function’s name from a non-constant-expression pointer to it is also possible but only via the use of a library that interprets the symbol table and/or debugging information.
Upvotes: 0
Reputation: 98
This is not possible with standard C++. Demangling the typeid won't help either because you're only going to get the name of the type of the function, not the name you actually gave the function.
The closest you can get is the predefined __func__
constant, but that only exists inside the scope of the function you'd want to get the name of anyways.
void foo()
{
std::cout << __func__; // will print "foo"
}
Upvotes: 2
Reputation: 12710
It's not possible in standard C++, but some compiler/libraries may have a way to work around that.
For example, gcc's libstdc++ has an extension which could demangle a typeid
value:
#include <cxxabi.h>
std::cout << typeid(type).name() << " -> " abi::__cxa_demangle(typeid(type).name(), 0, 0, 0) << std::endl
Upvotes: 0