没有宏的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模式下)来获得非宏反射的重要级别。有一些相关的机制可以反映"string-value";
- 见https://github.com/apolukhin/magic_get;
- 和https://github.com/Neargye/magic_enum .
相关文章:
- 你能重载对象变量名本身返回的内容吗
- 在C/C++中将变量名定义为__00000001有什么好处吗
- C++变量名(可以将 main 声明为变量,但对于其他函数名称则不然)
- 为什么我的字符串变量没有打印完整的字符串?
- C++ - 声明中变量名后面的括号
- 如何使替换 c 函数的变量名成为错误?
- 为什么变量的打印地址在每次执行时都会打印随机值,即使它是 C 中的逻辑地址?
- 是否可以创建没有变量名的变量
- fstream库,试图创建一个变量名为(c++)的文件
- 一个数组C++中的消息和变量名
- 在变量名后声明带有 () 的非内部类型与不使用变量名的行为不同。即 std::map<int,char>x(); - 这是怎么回事?
- 打印一个变量将打印另一个变量的值(以 C++ 为单位)
- C++ 类变量未打印分配的正确值
- 如何在实例化类类型的变量时打印其名称
- 数组的变量名和该数组的地址有什么区别?
- 未使用的变量禁止打印?
- 如何将变量名设置为字符串?C++
- 类中具有相同变量名的多重继承
- 在#define中打印变量名
- 没有宏的c++简单反射:打印变量名及其值