I'm new to C++, and unfortunately I cannot stop thinking in C# (my former language). I read some books, forums and the C++ reference website, but I couldn't find an answer to my question, so I thought I might as well try here before giving up and writing something ugly.
Ok, we can start. I have a class with an abstract method succesorsFunction and I would like it to return a collection of pointers to State. I don't want to force the implementors to a specific container; I rather let them choose (vector, list, etc).
So it looks like this:
class Problem
{
public:
virtual list<const State*>::iterator succesorsFunction(const State &state, list<const State*>::iterator result) const = 0;
};
the problem here is the explicit use of list. How do you do it in C++?
I thought about using templates, but then I encountered two problems: 1) It seems like you cannot do it with abstract methods (or am I wrong?) 2) How do I tell the template it should contain pointers to State?
Generic collections in C# include <List> , <SortedList> , etc.
The generic collections are introduced in Java 5 Version. The generic collections disable the type-casting and there is no use of type-casting when it is used in generics. The generic collections are type-safe and checked at compile-time. These generic collections allow the datatypes to pass as parameters to classes.
Generic functions are functions declared with one or more generic type parameters. They may be methods in a class or struct , or standalone functions. A single generic declaration implicitly declares a family of functions that differ only in the substitution of a different actual type for the generic type parameter.
Use generic types to maximize code reuse, type safety, and performance. The most common use of generics is to create collection classes. The . NET class library contains several generic collection classes in the System.
You can't overload methods based on return types in C++.
Also, "containers" in C++ don't have the same base (like Collection
in Java), so you can't return a generic container.
I'm afraid there's no clean way of doing this.
I would just write overloads (by parameter) or different function names.
For your questions:
1) You can. What makes you think you can't?
2) The same way you declared list
: list<const State*>
- const
is optional.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With