我想做以下事情:
template<typename Func>
class FunctionWrapper
{
public:
typedef decltype(Func()) ReturnType;
typedef ... ArgsType;
FunctionWrapper(Func func)
{
func_ = func;
}
ReturnType operator() (ArgsType args)
{
return func_(args);
}
private:
Func func_;
};
问题是我不知道如何从Func类型中推断出ArgsType。当函数返回/不接受任何内容时,我想让它工作。
然后用例将是:
FunctionWrapper<myFunction> wrapper;
auto result = wrapper(1, 2, 3);
答案 0 :(得分:1)
您可以在operator()
中确定参数和返回类型,并使用完美转发:
template <typename Func>
class FunctionWrapper
{
Func func_;
public:
FunctionWrapper(Func func) : func_(func) {}
template <typename... Args>
auto operator() (Args&&... args)
-> decltype(func_(std::forward<Args>(args)...)) {
return func_(std::forward<Args>(args)...);
}
};
答案 1 :(得分:0)
没有通用的方法可以做到这一点,也不符合逻辑。只需考虑Func
重载operator()
并接受不同参数类型的情况。但是,您可以强制Func
将其参数类型定义为FunctionWrapper
等实用程序要访问的成员类型。有关示例,请参阅std::function的可能成员类型。