可变模板工厂函数

Variadic Templated Factory Function

我正在寻找为数学向量 class 创建一个 "factory function" 的模板,该数学向量针对大小和类型进行了模板化。这是 class:

的声明
template<class T, std::size_t n>
class Vector {
  std::array<T, n> elements;

public:
  Vector();
  explicit Vector(std::array<T, n>& elements_);
  explicit Vector(const Vector<T, n>& v);
  explicit Vector(Vector<T, n>&& v);
  ~Vector() noexcept = default;
  Vector<T, n>& operator =(const Vector<T, n>& v);
  Vector<T, n>& operator =(Vector<T, n>&& v);
  T& operator [](std::size_t i);
};

这个想法是,必须先创建一个数组然后从中创建一个向量是很烦人的。我想要一个名为 make_vector 的可变参数函数,它采用 n 相同类型的参数 T 和 returns 该类型和大小的向量。这是我的尝试:

  template<class T, class... Ts>
  Vector<T, sizeof...(Ts) + 1> make_vector(T v1, Ts... args) {
    const std::size_t sz = sizeof...(Ts) + 1;
    std::array<T, sz> vals = {v1, args...};
    return Vector<T, sz>{vals};
  }

但是,我收到以下令人困惑的错误:

In file included from main.cpp:6:
In file included from ./oglmath.hpp:3:
In file included from ./vector.hpp:79:
./vector.tpp:14:31: warning: suggest braces around initialization of subobject
      [-Wmissing-braces]
    std::array<T, sz> vals = {v1, args...};
                              ^~~~~~~~
                              {       }
main.cpp:32:17: note: in instantiation of function template specialization
      'ogl::make_vector<float, float, float>' requested here
  vertices[0] = make_vector(-1.0f, -1.0f, 0.0f);
                ^
In file included from main.cpp:6:
In file included from ./oglmath.hpp:3:
In file included from ./vector.hpp:79:
./vector.tpp:15:12: error: no matching constructor for initialization of 'Vector<float,
      sizeof...(Ts) + 1>'
    return Vector<T, sz>{vals};
           ^~~~~~~~~~~~~~~~~~~
./vector.hpp:13:5: note: candidate constructor not viable: requires 0 arguments, but 1
      was provided
    Vector();
    ^
In file included from main.cpp:6:
In file included from ./oglmath.hpp:3:
In file included from ./vector.hpp:79:
./vector.tpp:42:12: error: non-const lvalue reference to type 'Vector<[2 * ...]>' cannot
      bind to a temporary of type 'Vector<[2 * ...]>'
    return Vector<T, n>(v);
           ^~~~~~~~~~~~~~~
main.cpp:32:15: note: in instantiation of member function 'ogl::Vector<float,
      3>::operator=' requested here
  vertices[0] = make_vector(-1.0f, -1.0f, 0.0f);
              ^
1 warning and 2 errors generated.

真的吗?它能找到的唯一构造函数是微不足道的构造函数?这是怎么回事!?如果我尝试在我的 Ts 中使用不同的类型,我完全预料到这会以一种奇怪的方式失败,但我很小心地让它们全部浮动!另外,为什么它对我 std::array 的初始化很生气?我尝试添加护腕,结果 错误 而不是警告。

我们看不到你的用法,但我们可以看出,在几个地方,你的复制初始化依赖于隐式转换,而这种转换不可用。

explicit 在复制 ctor 上是不寻常的;我认为我从未见过需要它的案例。

从复制构造函数中删除 explicit