简体   繁体   中英

C++ inheritance and templates

I have a List template.

I want to make a list of Jobs. However, I have different jobs when the only different thing is the function executeJob().

So I have a class Job:

class Job{...
...
public:
..
virtual SomeType executeJob() = 0;
}

So it's actually an abstract class and in the derived classes all the private fields are the same and it has the implementation for its own executeJob().

Lets say there are 2 different type of derived classes called Job1 and Job2 so I actually want my list to be able to have Job1 objects and job2 Objects as well.

My list is defined this way: List<Job> .

But in the ListNode c'tor I have this:

    listNode(const T& value) : value(new T(value)), prevNode(NULL),
    nextNode(NULL){}

and of course I have a problem with the line: value(new T(value)) as it's an abstract class. How do I solve it so I still can hold a list of both Job1 and Job2 objects and define it as List<Job> ?

Simple, you can't take T in the constructor.

You need a templated constructor, that takes the real class. Then you will call the constructor on the type of the parameter.

If you don't have the type, and only pass around "Job", then you will have to switch to prototype based design with a virtual clone() method (instead of calling the constructor).

Edit: Since you are using new , I'm assuming that the List<Job> is a typo and you meant List<Job*>

You cannot have a list containing different objects.

You could have a list of pointers to base class though.

The thing that the other answers are not covering well is that when you have a templated class C and you instantiate that class with two different template types, for all practical purposes the compiler sees these as being two distinct classes, not one class instantiated in two ways.

The types are incompatible unless you take the suggestion provided of storing pointers to a base class in your list. This way, if B and D derive off of A, then you can store B*'s and D*'s in the list, but access them through an A*.

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