首页 > 解决方案 > 将成员函数的默认实现保留在专门的模板类中

问题描述

目前正在尝试编写一些矢量数学代码,我想通过将各种结构专门化为不同的大小来做到这一点。但是,在这种特化中,非特化结构的成员函数会丢失。

最小示例:

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未定义。这似乎是一个非常常见的专业化用例,所以有可能做到这一点,如果没有,是否有语言设计原因导致这不可能?

(我知道我可以将代码复制到专门的结构中,我试图避免这种情况)

标签: c++templates

解决方案


推荐阅读