[英]C++ template arguments
我有一個制作矢量的模板。 默認構造函數分配n個相同的值元素。 第二個構造函數使用給定的參數創建一個向量。 由於第二個構造函數使用默認構造函數來定義向量,因此我只能給出有關此向量中有多少元素以及它們的值的參數。
public:
vector<float> coords;
Vector<n> (){
coords.assign(n, 0.0);
}
Vector<n> (vector<float> crds){
coords.assign(crds.size(),0.0);
}
理想情況下,第二個構造函數應該使用crds並檢查它的大小。 然后分配零次數與crds的大小相同 。 如果大小為2,它的效果很好。但是如果大小大於或小於2,則會發出錯誤。
如果我得到這個工作,那么我會在crds中插入每個值並彈出不必要的零。 但目前我無法找到另一種解決方案。 +我沒有找到任何其他適合我的矢量stl函數比分配更好。
我檢查結果的代碼是
Vector<2> v2 (vector<float>(2,3));
這就是我認為你要求的。 第二個構造函數中的代碼復雜性確保我們不會復制額外的值,只是為了擦除它們。
#include <vector>
#include <algorithm>
#include <cassert>
// untested
template <std::size_t n>
struct Vector {
std::vector<float> coords;
Vector() : coords(n, 0.) {}
Vector(const std::vector<float>& crds)
: coords(crds.begin(),
crds.begin()+std::min(n, crds.size())) {
// resize() extends coords with 0.0 values
coords.resize(n);
}
};
int main () {
std::vector<float> v(3);
Vector<6> V(v);
assert(V.coords.size() == 6);
}
#include <vector> #include <algorithm> #include <cassert> // untested template <std::size_t n> struct Vector { std::vector<float> coords; Vector() : coords(n, 0.) {} Vector(const std::vector<float>& crds) : coords(crds) { } }; int main () { Vector<6> V1; Vector<6> V2(std::vector<float>(3, 2.)); Vector<6> V3(std::vector<float>(10, 3.)); assert(V1.coords.size() == 6); assert(V2.coords.size() == 3); assert(V3.coords.size() == 10); }
如果您的編譯器提供了c ++ 11功能,則可以使用std::initializer_list
從值列表初始化std::vector
或Vector
。
#include <vector> #include <algorithm> #include <cassert> #include <initializer_list> // untested template <std::size_t n> struct Vector { std::vector<float> coords; Vector() : coords(n, 0.) {} Vector(const std::vector<float>& crds) : coords(crds) { } Vector(std::initializer_list<float> list) : coords(list) {} }; int main () { Vector<6> V1; Vector<6> V2(std::vector<float>(3, 2.)); Vector<6> V3(std::vector<float>(10, 3.)); Vector<6> V4(std::vector<float> ({1, 2, 3, 4})); Vector<6> V5({1, 2, 3, 4}); assert(V1.coords.size() == 6); assert(V2.coords.size() == 3); assert(V3.coords.size() == 10); assert(V4.coords.size() == 4); assert(V5.coords.size() == 4); }
如果我理解你想做什么,只需使用標准的矢量構造函數就可以做你想要的:
#include <vector>
template <int N>
class Vector {
public:
std::vector<float> coords;
Vector ()
: coords(N, 0.0f)
{}
Vector (const std::vector<float> & crds)
: coords(crds)
{}
};
但是,正如其他人在評論中強調的那樣,這似乎設計得很差(特別是,我無法理解為什么N
在兩個構造函數中的作用都是如此不對稱)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.