有没有办法将函数参数读取为在 C++ 中传递的确切名称?

Is there a way to read the function parameter as the exact name passed in 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 都将消失。但是如果您不介意使用一些包装器,您可以使用字符串化运算符 # 来模拟它。某些实现中的 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

Operator # 在编译前将结果放入已处理的源代码之前,字面上将以下标记用引号括起来,因此语句 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);
}

除了调试目的,这几乎没有用。