1234
Point<int, 3> p3a(1,2,3); // OK, array values set to 1, 2, 3 Point<int, 3> p3b(1,2); // OK, array values set to 1, 2, 0 Point<int, 3> p3c(1,2,3,4); // compiler error! Point<double, 10> p10a(1,2,3,4,5,6,7,8,9,10); // OK
123456789101112131415161718
#include <iostream> #include <vector> template< typename T, unsigned int N> struct Point { template <typename ... Args> Point(const Args& ... args): elements_{ args... }; std::vector<T> elements_; }; int main() { Point<int, 2> p(1,2); return 0; }
123456789101112131415161718192021222324252627282930313233343536
#include <iostream> #include <vector> #include <string> #include <initializer_list> using namespace std; template <typename T, unsigned int N> struct Point { std::vector<T> elements_; Point(std::initializer_list<T> lst) { for( const T& i : lst) { elements_.push_back(i); } } // added operator[] to treat object like a normal array T& operator[](int i) { return elements_[i]; } }; int main() { const int SIZE = 5; Point<int, SIZE> p{1, 2, 3, 4, 5}; // notice curly braces, not parentheses for(int i = 0; i < SIZE; i++) std::cout << p[i] << " "; }