繁体   English   中英

C++ 没有宏的简单反射:打印变量名及其值

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

C++ 中是否有非宏方式打印变量名称及其值。 这是宏方法:

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

PS:我用的是Linux,不需要跨平台方案

不,C ++不支持反射,这样做的唯一方法(据我所知)是宏。

您可以使用动态符号,但它只能在使用-rdynamic标志编译的共享库或可执行文件中工作。 它只会识别具有默认动态可见性的全局变量。

#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

没门。

没有宏,你必须这样做:

std::cout <<"a : " << a << std::endl; 

没有其它的方法。

如果您可以将所有类派生自共同的祖先,则可以提供实现此功能的虚函数。 我没有尝试过这个模板,它可能不起作用 - 一些反馈将不胜感激。

struct Reflector
{
    virtual void Show() = 0;
};
template<class a, char name[]>
struct ReflectorImpl : public Reflector
{
    virtual void Show()
    {
        std::cout << name << ": " << *this << std::endl;
    }
};

class MyClass: public ReflectorImpl<MyClass, "MyClass">
{
};

是的; 在 C++17 中,您可以使用 PFR(在 C++17 模式中)来获得非平凡级别的非宏观反射。 有反映枚举的“字符串值”的相关机制。

  1. 参见https://github.com/apolukhin/magic_get
  2. https://github.com/Neargye/magic_enum

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM