Point class and variadic template

Hi,

I am trying to implement a simple Point class using variadic templates as
discussed here [1]. My goal is to have this output possible:

1
2
3
4
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 


Here is my implementation so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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;
}


When I try to compile this, it fails. I don't understand why... Any thoughts?

Thank you.

[1] http://stackoverflow.com/questions/11891192/c-templates-simple-point-class
You need to use std::initializer_list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#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] << " ";
}



You can add additional functionality to this class/struct as you wish.
Last edited on
Thanks Arslan7041 !
Topic archived. No new replies allowed.