c++ - 将成员函数的默认实现保留在专门的模板类中
问题描述
目前正在尝试编写一些矢量数学代码,我想通过将各种结构专门化为不同的大小来做到这一点。但是,在这种特化中,非特化结构的成员函数会丢失。
最小示例:
template <size_t N> struct Vector {
float data[N];
inline float &operator[](size_t i) { return data[i]; }
inline constexpr float &operator[](size_t i) const { return data[i]; }
};
template <> struct Vector<2> {
union {
float data[2];
struct {
float x, y;
};
};
};
int main() {
Vector<2> v2 = {1, 3};
std::cout << v2[0] << " = " << v2.x << " | " << v2[1] << " = " << v2.y
<< std::endl;
}
此代码无法编译,因为operator[]
onv2
未定义。这似乎是一个非常常见的专业化用例,所以有可能做到这一点,如果没有,是否有语言设计原因导致这不可能?
(我知道我可以将代码复制到专门的结构中,我试图避免这种情况)
解决方案
推荐阅读
- r - Additionnal warning message returns an error instead of a warning
- windows - Heroku CLI 身份验证问题
- javascript - 在两点之间生成固定的经纬度
- windows - 奇怪的 AD 工作站访问问题
- api - Google Places API 搜索,而不是 20 个结果,我可以得到低于 20 个等 10 个等吗?
- c# - 插入多条记录以获取所有id时如何在c#中使用输出子句?
- javascript - 单击按钮时在模式上显示网站?
- html - 无法让对象在 div 底部对齐
- javascript - Javascript if or switch statement to add a class
- php - 检查在线花费的总时间从数据库中获取日期时间值并使用 php 按日期过滤它们