實際上在前一段時間,類似的代碼實現了。因此,嘗試下面的代碼:
template<unsigned N, unsigned M>
struct call_up_impl{
template<class Func, class Mutator, class Tuple, class... Args>
static void do_call(const Func& func, const Mutator& mutator, const Tuple& args, Args&&... unpacked_args) {
call_up_impl<N-1, M>::do_call(func, mutator, args, std::get<N-1>(args), std::forward<Args>(unpacked_args)...);
}
};
template<unsigned M>
struct call_up_impl<0, M> {
template<class Func, class Mutator, class Tuple, class... Args>
static void do_call(const Func& func, const Mutator&, const Tuple&, Args&&... unpacked_args) {
func(std::forward<Args>(unpacked_args)...);
}
};
template<unsigned M>
struct call_up_impl<M, M> {
template<class Func, class Mutator, class Tuple, class... Args>
static void do_call(const Func& func, const Mutator& mutator, const Tuple& args, Args&&... unpacked_args) {
call_up_impl<M-1, M>::do_call(func, mutator, args, mutator(std::get<M-1>(args)), std::forward<Args>(unpacked_args)...);
}
};
template<int i, typename Function, typename... Parms>
void apply(Function f, Parms... parms) {
std::tuple<Parms...> t(parms...);
call_up_impl<std::tuple_size<decltype(t)>::value, i + 1>::do_call(f, &g, t);
}
這是我原來的代碼快速適應,所以它不是徹底的測試,也許不是不是最佳的方式做到這一點,但它應該工作至少(至少根據快速測試,並取決於你想要什麼)。應該可以在沒有元組的情況下做到這一點,但我還沒有得到這個用g ++編譯(它似乎不喜歡所需的嵌套variadic模板)。然而改變apply
到:
template<int i, typename Function, typename... Parms>
void apply(Function f, Parms&&... parms) {
std::tuple<Parms&&...> t(std::forward<Parms>(parms)...);
call_up_impl<std::tuple_size<decltype(t)>::value, i + 1>::do_call(f, &g, t);
}
將可能避免了大部分的元組引入的開銷。如果要正確轉發std::get
調用的結果會更好,但我現在太累了,無法將其寫入。
pi在math.h中可用作M_PI。不知道其餘的,你可以用更少的省略號發佈代碼嗎? – 2012-01-11 01:13:18
@HansPassant我覺得OP意味着'第i parameter'通過'pi' – 2012-01-11 01:14:07
@HansPassant C++現在去整個方式:你不必再編寫所有的代碼!省略號實際上是代碼並正在執行! – 2012-01-11 01:16:44