template<class F_before, class F, class F_after>
struct decorate_func_t {
F_before f0;
F f1;
F_after f2;
template<class...Args>
typename std::result_of<F(Args...)>::type operator()(Args&&...args)const{
f0();
auto r = f1(std::forward<Args>(args)...);
f2();
return r;
}
};
template<class F_before, class F, class F_after>
decorate_func_t<F_before, F, F_after>
decorate_func(F_before before, F f, F_after after){
return {std::move(before), std::move(f), std::move(after)};
}
然后:
template <typename F, typename Args...>
inline auto runFunc(F func) -> foo
{
return foo(decorate_func(
[]{/* Do something before calling func */},
func,
[]{/* Do something after call func */ }
};
}
在C++ 11缺乏auto
参数lambdas使得你可以做的最好。
在C++ 14这个很简单:
template <class F>
auto runFunc(F func)
{
return foo(
[func](auto&&... args) // ->decltype(auto) maybe
{
// Do something before calling func
auto r = func(decltype(args)(args)...);
// Do something after call func
return r;
}
);
}
注意,很多名义上是C++ 11编译器实际上支持lambda表达式auto
参数。
你能提供更多关于你想要做什么的背景吗? – templatetypedef
'runFunc(F func)'后的' - > foo'没有任何意义。试试'decltype(foo([func](Args ... args)'...'))' – Czipperz
什么是'foo()'?你只是想装饰'func'? – Barry