我正在嘗試做一些解析度結構,它只保存我的螢屏寬度和高度。我將在某些方面大量使用它,有些方法需要像向量這樣的資料,有些則需要像內部結構一樣的資料。
例子:
template<typename InternalType>
struct Resolution
{
InternalType width_;
InternalType height_;
std::vector<InternalType> vectorRepr()
{
return std::vector<InternalType>{width_, height_};
};
Vector2 vectorRepr()
{
return Vector2{width_, height_};
};
// maybe some other overloadings of vectorRepr()
}
上面的示例不起作用,因為 vectorRepr 嚴重過載。
我想要實作的是在 Resolution struct 封裝的方法中以不同的資料型別回傳我的內部狀態。模板專業化可能會派上用場,但我很難加入解析度模板和 vectorRepr 模板的想法。
對我來說,它看起來類似于部分模板專業化。
接近 std::vector 回傳型別:
template<> // <- this is a specialization for vectorRepr
std::vector<InternalType> vectorRepr<std::vector>()
{
// but here, vector should know the InternalType, to embed it.
// so the InternalType is not specialized.
return std::vector<InternalType>{width_, height_};
}
在這里,我找到了有趣的示例(但它缺少要回傳的成員屬性): 如何使用模板型別專門化模板函式
I am aware it can be done easy in different way, but at this point I'm just to curious.
Is it achivable ?
Playground:
https://godbolt.org/z/bE49vv3Ms
uj5u.com熱心網友回復:
在顯示的示例中,我認為不需要任何專業化,部分或其他。這就足夠了:
template <typename Ret>
Ret vectorRepr() {
return {width_, height_};
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/438901.html
