简体   繁体   中英

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.

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;

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...

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM