我有以下功能:
template <uint8_t N1, uint8_t N2, uint8_t N3>
Shape<N3> func(const Shape<N1> &shape1, const Shape<N2> &shape2)
{
return Shape<N3>();
}
形狀的定義:
template <uint8_t N> class Shape;
有沒有辦法通過傳遞給函式的形狀來推斷 N1 和 N2?
Shape<3> shape1 = {1, 2, 3};
Shape<2> shape2 = {4, 5};
Shape<4> shape3 = func<4>(shape1, shape2);
代替:
Shape<4> shape3 = func<3, 2, 4>(shape1, shape2);
謝謝你的幫助!
uj5u.com熱心網友回復:
您應該安排模板引數,以便需要顯式指定的引數位于開頭,可以從引數中推斷出的引數位于末尾:
template <uint8_t N3, uint8_t N1, uint8_t N2>
Shape<N3> func(const Shape<N1> &shape1, const Shape<N2> &shape2)
{
return ...;
}
Shape<3> shape1 = {1, 2, 3};
Shape<2> shape2 = {4, 5};
Shape<4> shape3 = func<4>(shape1, shape2);
在這里,N3顯式指定為 4 whileN1并且N2是從引數型別推匯出來的,因此所有模板引數都有值并且代碼可以編譯。如果你N3最后離開,那么你將被迫顯式指定N1并N2為了顯式指定N3.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/410973.html
標籤:
