I have a pointer to an int
object.
int x = 10;
int *ptr;
ptr = &x;
I want to write a function GetString(int *ptr)
which would return me the string ptr
. How do I do that in C++?
I have a pointer to an int
object.
int x = 10;
int *ptr;
ptr = &x;
I want to write a function GetString(int *ptr)
which would return me the string ptr
. How do I do that in C++?
There isn't a direct way to extract a variable's string name in C++. The language has only rudimentary reflection features, see the type_traits standard library and SO post Why does C++ not have reflection?.
But you can use preprocessor stringification #
to hack something similar: define
#define STRINGIFY(x) #x
then the preprocessor substitutes STRINGIFY(ptr)
with the string "ptr"
.
Note: if you want to stringify the result of a macro expansion use two levels of macros.
#include <iostream>
#include <map>
const std::string& getString(int *ptr, const std::map<int*, std::string>& mp){
return mp.find(ptr)->second;
}
int main()
{
std::map<int* , std::string> mp;
int x = 10;
mp.insert({&x, "ptr1"});
int y = 9;
mp.insert({&y, "ptr2"});
std::cout << getString(&y, mp);
}