我之前發布了一個問題,解壓縮可變引數并相應地傳遞它的元素。但是,它并沒有完全解決我的問題,因為我沒有準確地問它。因此,我想重新措辭并詳細解釋我的問題。提前致謝!
假設我有一個結構Outcome
,它需要一個兩個引數的函式Outcome cal_out(int, int)
來構造,并且可以使用兩個附加引數進行遞回計算Outcome cal_out(Outcome, int, int)
,即x
和y
。
struct Outcome {
int valueX;
};
Outcome cal_out(int x,int y) {
int z = some_algo(x, y);
return Outcome{z};
}
Outcome cal_out(Outcome rhs, int x, int y){
int z = some_algo(rhs, x, y);
return Outcome {z};
}
template<class... Ts>
Outcome cal_out(Outcome rhs, int x, int y, Ts... ts){
return cal_out(cal_out(rhs, x, y), ts...);
}
現在我的問題是,我有一個Coord
這樣的結構。
template<int X, int Y>
struct Coord {
static const int valueX = X;
static const int valueY = Y;
};
我想問一下如何打電話get_out_from_coords()
來獲得結果,即
Outcome out = get_out_from_coords<Coord<1,2>, Coord<3,4>, Coord<5,6> >();
我的偽實作不起作用
template<class COORD>
Outcome get_out_from_coords() {
return cal_out(COORD::valueX, COORD::valueY);
}
template<class COORD1, class COORD2>
Outcome get_out_from_coords() {
return cal_out(get_out_from_coords<COORD1>(), COORD2::valueX, COORD2::valueY);
}
template<class COORD1, class COORD2, class... COORDs>
Outcome get_out_from_coords() {
return cal_out( get_out_from_coords<COORD1, COORD2>(), COORDs::valueX, COORDs::valueY...);
//manipulating the pack expressions to get something like this
}
注意:Outcome
不能以這種方式計算Outcome cal_out(Outcome, Outcome)
所以,像折疊運算式這樣的東西在這種情況下不起作用。IE
template<class... COORDs>
Outcome get_out_from_coords() {
return cal_out(cal_out(COORDs::valueX, COORDs::valueY)...);
}
uj5u.com熱心網友回復:
template<class... COORDs>
Outcome get_out_from_coords() {
return std::apply(
[](int x, int y, auto... args){ return cal_out(cal_out(x, y), args...); },
std::tuple_cat(std::make_tuple(COORDs::valueX, COORDs::valueY)...)
);
}
這只是連接所有valueX
/valueY
對并cal_out
使用這些引數呼叫。這里假設一切都是按價值計算的,并且復制引數很便宜。如果不滿足這些條件,std::forward_as_tuple
則應使用 lambda 中的完美轉發。
我也覺得這cal_out
是以一種奇怪的方式定義的。我認為應該有一個不需要 a 的可變引數多載Outcome
,然后可以用
[](auto... args){ return cal_out(args...); }
作為 lambda 代替。否則,如果只有一個,則需要添加特殊情況COORDs
。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/470087.html