[英]C++ metaprogramming to split the function arguments and pass them one by one to another function
所以我有一個具有不同參數類型的可變參數函數; 我想將每個參數傳遞給另一個函數,它是一個 C 函數。 舉個例子; 對於有兩個參數的情況;
void function(int *a, double *b) needs to call
{
bindToFunc(0, a);
bindToFunc(1, b);
}
void function(int *a, double *b, float *c) needs to call
{
bindToFunc(0, a);
bindToFunc(1, b);
bindToFunc(2, c);
}
template<typename... T>
void function(T ...)
{
// has to have
//
// bindToFunc(0, T0) ....
// bindToFunc(n-1, Tn-1);
}
我嘗試使用,
template <int I, class... Ts>
decltype(auto) get(Ts &&... ts)
{
return std::get<I>(std::forward_as_tuple(ts...));
}
但由於 I 是模板參數,它是一個編譯時變量,因此我們不能在 for 循環中使用它。
使用 C++17 和fold expression ,你可以這樣做:
template<typename... Ts>
void function(Ts... args)
{
[[maybe_unused]] int i = 0; // Not used for empty pack.
(bindToFunc(i++, args), ...);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.