c++ - 有没有办法将函数参数读取为在 c++ 中传递的确切名称?
问题描述
对于我的程序 (C++),我需要读取函数参数之一,因为它是在调用函数时给出的,例如:
void foo(int arg)
{
// I need to read the "arg" parameter here, not its value but the exact thing passed while calling the "foo" function
}
for example:
int bar = 10;
foo(bar); // I want to read "bar" string
有没有办法做到这一点?
我可以看到的替代选项之一是制作两个参数并调用如下函数:
foo(bar, "bar");
我是 C++ 的初学者,所以这可能是一个愚蠢的问题......
解决方案
由于 C++ 中没有内置反射,因此在生成的代码中所有 id 都将消失。但是如果你不介意使用一些包装器,你可以使用 stringize operator # 来模拟它。assert() 宏在某些实现中使用它。
#include <iostream>
void order(int arg1, int arg2, const char* str)
{
std::cout << str << arg1*arg2 << std::endl;
}
#define REFLECT_INVOKE(func, ...) (func)(__VA_ARGS__, #func "(" #__VA_ARGS__ ") = ")
int main()
{
int x = 6;
int y = 11;
REFLECT_INVOKE(order,x,y);
}
输出:
order(x,y) = 66
运算符 # 在编译前将结果放入已处理的源代码之前,将后面的标记字面上用引号括起来,因此语句REFLECT_INVOKE(order,x,y);
被处理为(order)(x,y,"order" "(" "x,y" ") = ");
我们可以让它更通用一点,使用新功能(可能有简单而明显的方法来做到这一点):
int order(int arg1, int arg2)
{
return arg1*arg2;
}
template<class F, class ...Args>
auto debug_call( F func, const char* str, Args... args) ->
decltype(std::forward<F>(func)(std::forward<Args>(args)...))
{
if constexpr ( std::is_same<decltype(std::forward<F>(func)(std::forward<Args>(args)...)),void>::value) {
std::cout << str;
func(args...);
} else {
auto res = func(args...);
std::cout << str << "= " << res;
return res;
}
}
#define REFLECT_INVOKE(func, ...) (debug_call)(func, #func "(" #__VA_ARGS__ ") ", __VA_ARGS__)
int main()
{
int x = 6;
int y = 11;
REFLECT_INVOKE(order,x,y);
}
除了调试目的之外,这几乎无法使用。
推荐阅读
- python - 设置用户友好和显式标志值的大多数 Pythonic 方式?
- mysql - 我无法在我的 docker compose 中进行 mysql php artisan 迁移。错误 SQLSTATE[HY000] [2002]
- javascript - 根据属性合并对象数组中的元素
- excel - 检查是否已设置工作簿变量
- excel - 突出显示两列中的重复单元格
- javascript - 使用 Greasemonkey 删除特定的 javascript 函数
- javascript - 角度 || 在加载 Dom html 元素但在 Angular 应用程序中显示为空的视图中,我使用了供应商(第三方主题)库和 Angular 材料
- python - 尝试使用 python 使用 Selenium 单击单选按钮
- javascript - 实时更新填充有 Django 值的 HTML 字段
- python - Does calculations take place when I assign a statement to a variable or when that variable is called