You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用可变类型参数的可变参数宏生成转发参数的包装函数

可变参数包装函数宏的实现问题

我现有一个宏:

#define WRAP_FUNCTION(wrapper_name, function, ret_type, arg1_type, arg2_type, ...)

希望它能定义出如下形式的函数:

ret_type wrapper_name(arg1_type arg1, arg2_type arg2, ...) {
    return function(arg1, arg2, ...);
}

其中省略号(包含arg1和arg2)是动态长度的参数列表。我可以用__VA_ARGS__生成函数原型,但无法自动生成传递给被包装函数的参数名。

我原本考虑使用std::apply(或自行复制其实现,因为要兼容C++11),但function可能是重载函数或编译器内置函数,无法可靠地作为函数类型传递。

目前我实现的是生成可变参数模板函数:

template<class... Args>
ret_type wrapper_name(Args... args) {
    return function(std::forward<Args>(args)...);
}

但这个实现会引发转换问题:当被包装函数为重载函数时,很多隐式转换无法完成;同时它也无法包装类函数宏,不过这个问题可能无解。


更新:我调整实现后,让包装函数可以强制参数类型:

#define WRAPPER(name, ret_type, function, ...) \
  template<class... Args> struct name##_impl { static inline \
  ret_type func(Args... args) { return function(std::forward<Args>(args)...); } }; \
  template<class... Args> ret_type name(Args... args) \
  { return name##_impl<__VA_ARGS__>::func(std::forward<Args>(args)...); }

但新问题出现:无法用不同参数列表重载标识符name。尝试将name模板改为特化时,要么遇到函数偏特化的编译报错,要么无法向通用模板转发参数。

内容的提问来源于stack exchange,提问作者sh1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 05:07:14