I'm trying to build a constructor to take an array as an argument
(...)
explicit SmallVec(const U* vec) {
You are not taking an array. Do you take a pointer that may or may not point to an array , and even if it points to an array that says the array has at least three elements? This is a serious design flaw.
C ++ allows you to take raw arrays by reference or constant reference, although the syntax is terrible:
explicit SmallVec(const U (&vec)[3]) {
The constructor implementation is also different:
for(int index = 0; index < 3; ++index) { data[index] = static_cast<T>(vec[index]); }
If you look at main , the problem goes deeper. You use new[] to dynamically allocate the array. This is already a very bad idea. By the way, your example also skips delete[] . Why aren't you using a local array instead?
float arr[3];
This will make your program compile and probably work correctly, but it will still be undefined in your code, because you only set the 3rd element of the array to a valid value; the other two elements remain uninitialized, and reading from an uninitialized float , even if you just copy it, formally leads to undefined behavior.
So do it better:
float arr[3] = { 0.0, 0.0, 3.4 };
In addition to this, C ++ 11 suggests you use std::array , which usually makes things safer and improves the syntax. Here is a complete example:
#include <iostream> #include <array> template <typename T> class SmallVec { // This is a 3 dimensional vector class template public: std::array<T, 3> data; // internal data of class template <typename U> explicit SmallVec(const U& scalar) { // if a scalar, copy it to each element in data for(auto &item : data) { item = static_cast<T>(scalar); } } template <typename U> explicit SmallVec(std::array<U, 3> const& vec) { // if a vector, copy one by one for(int index = 0; index < 3; ++index) { data[index] = static_cast<T>(vec[index]); } } }; int main() { float num = 1.2; std::array<float, 3> arr = { 0.0, 0.0, 3.4 }; SmallVec<float> vec1(num); SmallVec<float> vec2(arr); std::cout << vec1.data[2] << " " << vec2.data[2] << std::endl; return 0; }