这里有一些有漏洞的代码:
template<typename... Args>
class A
{
typedef function_type = void(*)(Args...);
public:
void set_args(Args&& ... args)
{
// something magic manages to encapsulate
// args in instance of A
}
void apply_args(function_type function)
{
// something magic manages to "retrieve"
// the encapsulated args
function(std::forward<Args>(args)...);
}
};
这有可能吗?
最佳答案
您可以将模板参数存储在 std::tuple
的类数据成员中类型及用途 std::apply
以便将存储的参数应用于提供的函数。
那么,假设您有一个像这样的 Action
类:
template <typename... Args>
class Action {
std::tuple<Args...> args_;
public:
Action() = default;
Action(Args&&... args)
: args_(std::forward<Args>(args)...)
{}
void args(Args&&... args) {
args_ = std::make_tuple<Args...>(std::forward<Args>(args)...);
}
template <typename F>
void apply(F&& fun) {
std::apply(std::forward<F&&>(fun), args_);
}
};
通过构造函数 Action action(1, 2, 3);
或通过单独的函数 action.set(3, 2, 1);
设置参数。
那么你的主函数可以如下所示:
int main() {
Action action(1, 2);
action.apply([](int a, int b) {
std::cout << "a + b = " << (a + b) << std::endl;
});
return 0;
}
关于c++ - 将可变参数函数的参数封装在类实例中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60216917/