Variadic模板化工厂功能

时间:2015-07-20 15:00:37

标签: c++ c++11 variadic-templates

我希望创建一个"工厂功能"对于尺寸和类型模板化的数学Vector类。以下是该类的声明:

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的{​​{1}}个参数,并返回该类型和大小的向量。这是我的尝试:

T

然而,我收到以下令人困惑的错误:

  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的初始化感到生气?我尝试添加护腕,错误而不是警告。

1 个答案:

答案 0 :(得分:2)

我们无法看到您的使用情况,但我们可以说,在某些地方,您的复制初始化依赖于隐式转换,而无法进行此类转换。

副本上的

explicit是不寻常的;不要以为我曾经见过一个令人满意的案例。

从副本中删除explicit