S. Perfees
S. Perfees

Reputation: 3

Class with different types

I am working on a C++ ROS Project, which contains different classes, each containing a vector.

The difficulty is that the vectors can be of different types. For example:

class A{
    public
        .....
    private 
        std::vector<Class_C> List
}
class B{
    public  
        .....
    private 
        std::vector<Class_D> List
}

How could I achieve such task? I would like to find a way to simplify my code using templates, inheritances, and other language features.

Upvotes: 0

Views: 91

Answers (3)

Obi1
Obi1

Reputation: 38

Is that what you are looking for?

template <typename T>
class A {
    public:
        .....
    protected: 
        std::vector<T> List;
};

class B : public A<Class_D> {
    public:
    .....
};

B b;

Upvotes: 0

pandaman1234
pandaman1234

Reputation: 523

Since I cannot comment because of my reputation I have to write an answer, but Gill Bates' answer could solve your issue even though you are not clear on what you want to accomplish. And to extend on his answer you could use inheritance based of his template class to ease your coding and force a type into your list (you would also need to change your list visibility to protected in this case):

class FooInt : public A<int>{
    public
        void print() { /* print List's content */ }
...
};

class FooString : public A<std::string>{
    public
        void print() { /* print List's content */ }
...
};

You use your classes this way:

FooInt hello;
hello.print(); // Would print list of int

FooString moto;
moto.print(); // Would print list of string

Note that the classes' names are written as Foo* only to help you understand that their underlying lists would contain the types written in the names, this could be your class B inheriting from the class A...

Upvotes: 1

Hatted Rooster
Hatted Rooster

Reputation: 36483

Just use a template argument:

template <typename T>
class A{
    public
        .....
    private 
        std::vector<T> List;
}

This allows A to have a vector of any type:

A<Class_C> foo;
A<Class_D> bar;

Upvotes: 3

Related Questions