Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Simple Reflection without Macros: Print Variable Name and Its Value

Is there a non-macro way in C++ of printing a variable name with its value. Here is the macro way:

#define SHOW(a) std::cout << #a << ": " << (a) << std::endl

PS: I'm using Linux and do not need a cross-platform solution

like image 779
Alan Turing Avatar asked Jul 27 '11 19:07

Alan Turing


2 Answers

No, C++ does not support reflection and the only way of doing this (as far as I know) are with macros.

like image 151
Jacob Avatar answered Nov 16 '22 02:11

Jacob


You can use dynamic symbols, but then it will only work in shared libraries or executables compiled with the -rdynamic flag. And it will recognize just global variables with default dynamic visibility.

#include <dlfcn.h>
#include <iostream>

int NameMe = 42;

const char *GetName(const void *ptr)
{
    Dl_info info;
    if (dladdr(ptr, &info))
        return info.dli_sname;
    else
        return NULL;
}

    template<typename T>
void Dump(const T &t)
{
    const char *name = GetName(&t);
    if (name)
        std::cout << name;
    else
        std::cout << "<unknown>";
    std::cout << ": " << t << std::endl;
}
int main()
{
    int NoName = 33;
    Dump(NameMe);
    Dump(NoName);
    return 0;
}

$ g++ dump.cpp -ldl -rdynamic
$ ./a.out
NameMe: 42
<unknown>: 33
like image 22
rodrigo Avatar answered Nov 16 '22 02:11

rodrigo