List<>

I want to create a class X with 2 proprieties:

-string
-list

but i want to define the list items type when creating the new X object.

object1
name: "items"
list: (integers)

object2
name: "names"
list: (strings)

Thank u in advance!! :)
Last edited on
Does this look good?

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <string>
#include <list>

template <class T>
struct ListMaker
{
    std::list<T> lst;

    ListMaker & operator << (const T & n)
    {
        lst.push_back(n); return *this;
    }
};

template <class T>
class MyClass
{
    std::string str;
    std::list<T> lst;

public:

    MyClass(const std::string & str_,
        const ListMaker<T> & lst_mkr_):
            str(str_), lst(lst_mkr_.lst) {}

    void Print() const
    {
        std::cout << str << std::endl;

        typename std::list<T>::const_iterator it=lst.begin();
        typename std::list<T>::const_iterator end=lst.end();

        while (it!=end) std::cout << *it++ << " ";

        std::cout << std::endl;
    }
};

int main()
{
    MyClass<int> my_object1("hello, world!",
        ListMaker<int>() << 2 << 3 << 5 << 1 << 4 << 6);

    MyClass<double> my_object2("hello, again!",
        ListMaker<double>() << 5.5 << 1.25 << 2.75);

    my_object1.Print();
    my_object2.Print();

    return 0;
}

Useful link - > http://www.learncpp.com/cpp-tutorial/143-template-classes/
Last edited on
Thank u a lot!! it really helped ;)
Topic archived. No new replies allowed.