首页 > 解决方案 > 有没有办法将函数参数读取为在 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++functionparameters

解决方案


由于 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);
}

除了调试目的之外,这几乎无法使用。


推荐阅读