【发布时间】:2017-03-23 16:47:10
【问题描述】:
我尝试执行以下操作:
template <typename T, int N>
struct Vector {
T v[N];
template<typename... Args> Vector(Args... args) : v { args... } {}
template<typename S> Vector(Vector<S, N> const & V) : v {V.v} {}
};
int main() {
Vector<float, 4> V (1.0f, 2.0f, 3.0f, 4.0f);
Vector<float, 4> V2 (V);
for (auto f : V2.v) { cout << f << ", "; } cout << endl;
return 0;
}
而且它起作用了(打印为“1, 2, 3, 4,”),所以我没有怀疑任何事情,直到我尝试用“专门化它”:
Vector(Vector const & V) : v {V.v} {}
或与 :
一起使用 Vector<double, 4> V2 (V);
编译器说:
错误:初始化时无法将 'const float*' 转换为 'float'
或与'double'相同。
在那之后我尝试了简单的数组,但同样的错误失败了,但是有足够的模板它可以工作..
谁能给我解释一下这里发生了什么?
【问题讨论】:
-
你不能分配数组,你需要遍历复制它们的元素。
-
不能写
v1.v = v2.v;是同一个原因 -
停止使用哑数组并使用
std::array。它实际上与使用数组相同,没有您现在看到的所有陷阱,as this example shows
标签: c++ arrays templates initialization