开发者

C++: How do you convert the name of a function pointer to text?

Possible Duplicate:

How to get function's name from function's pointer in C?

I'm printing the configuration for the program to the command line each run, and one thing that I would like printed is the current hash function being used -- which is stored in a function pointer variable.

Is there a way to do something along the lines of:

std::cout << function_pointer.function_name_to_text() << "\n";

So like, if I have a function called sha1(char * pre_image), it would just output sha1 to the console? the entire method header would be grand t开发者_高级运维oo.


You can't get the function name at run-time since function names don't exist after compilation.

You can however build a separate lookup function that would save the name and associate it with the function pointer:

#include <iostream>
#include <map>
#include <string>
#include <boost/preprocessor/stringize.hpp>

typedef void (*fptr_t)(char*);
typedef std::map<fptr_t, std::string> function_map_t;
function_map_t fmap;

#define REGISTER_FUNCTION(f) fmap[f] = BOOST_PP_STRINGIZE(f);

void sha1(char*) {}  // a function you want to lookup

int main() {
      REGISTER_FUNCTION(sha1)
      fptr_t my_pointer = sha1;
      std::cout << "Function name is: " << fmap[my_pointer] << std::endl;
      return 0;
}

EDIT: Updated to compile


There is no way to do this in the C++ language as it does not support reflection. The __FUNCTION__ macro is a non-standard way to get the current (meaning what the compiler is now compiling) function name. It is built-in on many platforms, but not all. You might be able to use that to get close to what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜