Unique ID Defined by Most-Derived Class accessible through Base Class - c++

Okay, so, the idea is that I have a map of "components", which inherit from componentBase, and are keyed on an ID unique to the most-derived*.
Only, I can't think of a good way to get this to work. I tried it with the constructor, but that doesn't work (Maybe I did it wrong). The problem with any virtual, etc, inheritance tricks are that the user has to impliment them at the bottom, which can be forgotten and makes it less... clean.
*Right phrase? If -> is inheritance; foo is most-derived: foo->foo1->foo2->componentBase
Here's some code showing the problem, and why CRTP can't cut it:
(No, it's not legit code, but I'm trying to get my thoughts down)
#include<map>
class componentBase
{ public: virtual static char idFunction() = 0; };
template <class T>
class component
: public virtual componentBase
{
public:
static char idFunction(){ return reinterpret_cast<char>(&idFunction); }
};
class intermediateDerivations1
: public virtual component<intermediateDerivations1>
{
};
class intermediateDerivations2
: public virtual component<intermediateDerivations2>
{ };
class derived1
: public intermediateDerivations1
{ };
class derived2
: public intermediateDerivations1
{ };
//How the unique ID gets used (more or less)
std::map<char, componentBase*> TheMap;
template<class T>
void addToMap(componentBase * c)
{
TheMap[T::idFunction()] = c;
}
template<class T>
T * getFromMap()
{
return TheMap[T::idFunction()];
}
int main()
{
//In each case, the key needs to be different.
//For these, the CRTP should do it:
getFromMap<intermediateDerivations1>();
getFromMap<intermediateDerivations2>();
//But not for these.
getFromMap<derived1>();
getFromMap<derived2>();
return 0;
}
More or less, I need something that is always there, no matter what the user does, and has a sortable value that's unique to the most-derived class.
Also, I realize this isn't the best-asked question, I'm actually having some unexpected difficultly wrapping my head around it in words, so ask questions if/when you need clarification.
Edit:
Using Beta's phrasing; The class derived2 has an ID number, unique among all classes derived from ComponentBase, and from which no other classes are derived - except that there should be no usage cases in which we're dealing with an instance when we don't know the most-derived type. That is, we should never have to deal with a foo1* that is actually pointing to a ``foo`.
Any time that I need to access this ID, I have type information about the most-derived class; via the templated nature of addComponent, getComponent and removeComponent.
Hmm, to put it another way; I need to "convert" type into a unique number while I know the type, so that I can later distinguish between two things when I don't have the type information.

I don't understand why you are using reinterpret_cast in class component.
As far as having unique IDs, you should have some kind of process to validate that the ID is not used by any derived instance.
On the other hand, each class should implement a static clone or create method. The factory would have a map of . The function pointer points to the specific class' create or clone method. Since the std::map cannot be created as a const static entity during compilation time, I generally use constant static arrays to hold the IDs and function pointers. If the array is small, it is insignificant in performance to a map.
Example:
class Base
{;};
// Declare a synonym for a pointer to the creation function.
typedef Base * (*P_Creation_Function)(unsigned int id);
struct Creation_Entry
{
unsigned int class_id;
P_Creation_Function p_creator;
};
class Child1 : public Base
{
public:
static Base * create(unsigned int id);
};
Creation_Entry creation_table[] =
{
{1, Child1::create},
};
static const unsigned int NUM_CREATORS =
sizeof(creation_table) / sizeof(creation_table[0]);
// Process 1: search table for ID
for (unsigned int i = 0; i < NUM_CREATORS; ++i)
{
if (creation_table[i].class_id == new_id)
{
return (*creation_table[i].p_creator)(new_id);
}
}
// Process 2: Execute each creation function in the table.
// Creation functions will return NULL if the ID is not a match
Base * p_new_object;
for (unsigned int j = 0; j < NUM_CREATORS; ++j)
{
p_new_object = (*creation_table[j].p_creator)(new_id);
if (p_new_object)
{
return p_new_object;
}
}
For small projects, the overhead of a creation function return NULL is not significant compared to other bottlenecks (such as disk i/o). The second process does not require the factory to know the class ID; the class ID remains encapsulated in the class.
I've used both processes and implement them depending on my mood and the project size. :-)

You could make use of the typeid operator.
If you have a ComponentBase* component, then
typeid(*component)
will return a type_info& object that uniquely identifies the class of the object that the component pointer points at. (If component points at a Derived object, then this will return the type_info object that belongs to the Derived class. Note though that typeid(component) would return a type_info& that represents the type ComponentBase*, so dereferencing the pointer is important.)
Then you can use eg. the address of this type_info object, or the result of type_info::name() as the key for your map.

Related

c++ how to implement const static members in derived classes

In C++, I have several classes inheriting from an abstract super class. Subclasses have a static attribute sharing the same name type but of course have different values. My question is what is the best approach to implement this and what are the pros and cons for each implementation.
PS:
There are some related discussions like here but most don't explain why approach (which works on my machine) 1 below should not be used. Besides, the subclass methods in approach 2 are not static and wwe will have to get an instance to invoke them.
Apporach 1: uinitialized const static in superclass
class Abstract {
public:
const static int type;
};
class C1: public Abstract {
public:
const static int type = 1;
};
class C2 : public Abstract {
public:
const static int type = 2;
};
Approach 2: using virtual functions instead of variables
class Abstract {
public:
virtual int get_type() = 0;
};
class C1: public Abstract {
public:
int get_type() {return 1;}
};
class C2 : public Abstract {
public:
int get_type() {return 2;}
};
Other approaches that I'm not aware of...
EDIT:
As some answers/comments mentioned below, I'm trying to identify actual type at runtime. However I cannot really think of a nicer design.
To make it concrete, let's say Abstract=EduInst for educational institution, C1=Univ, C2=College, etc. I have a std::map<Key, EduInst*> storing all institutions, which are generated at runtime depending on user input. At times I need to operate only on Univs or Colleges. What is a good way to implement this?
First the warnings:
Inheritance describes an "is kind of" relationship with the base class. It only makes sense when you are storing different kinds of objects in the same container, when those kinds of object absolutely share the same interface, and when no special handling is required on any one of the derived classes (i.e. when you, the object's consumer don't need to know its type).
Furthermore, if you only have a few kinds of the same thing, and those kinds of thing can possibly be known at compile time, then it's probably a mistake to use inheritance.
If your inherited object must identify its actual type to a client, this is further evidence that inheritance is the wrong solution - since now you're going to use code to find code, which is a bad idea (it's not testable, and it's liable to go wrong when your program is in a state that you didn't anticipate).
Furthermore, if you have objects that are dissimilar but need to be stored in the same container, then boost::variant is probably the solution you're looking for. You would then use boost::static_visitor to perform operations on the object in the variant. The advantage of this is that is absolutely type-safe and the compiler won't allow you to forget to handle a type.
Having said all that...
approach 1 won't work because if you have the type of the derived class already, you'll always get the base class' type.
approach 2 will work but it's horrid and an indication of a broken design.
You can't have "virtual" static members.
Approach one is for finding out the "type" attribute of a class, the second for finding out the "type" attribute of an instance.
To put it differently: to use the first, you need to know the class; to use the second, you need to know the instance.
It's impossible to write code where you know neither.
Note that approach one can give you unexpected results if you use type inside a function in a base class.
For instance,
class Abstract
{
public:
int get_type() const { return type; }
};
// ...
C1 c;
std::cout << c.get_type();
will output 0, since that is the value of Abstract::type.
A variation of the second approach lets you avoid the virtual function if you sacrifice the space of another member:
class Abstract {
public:
// ...
int get_type() const { return type; }
protected:
Abstract(int t) : type(t) {}
private:
int type;
};
class C1: public Abstract {
public:
C1() : Abstract(1) {}
};
class C2 : public Abstract {
public:
C2() : Abstract(2) {}
};

Abstract base member variable in base class

I want to specify an interface which requires an abstract class to have a certain type as a member variable.
I'll try to replicate the situation here:
class Blob {
int data[32];
};
class Worker {
string name;
abstract void workOn(Blob&) = 0;
}
class Abstract {
vector<shared_ptr<W>> workerList;
Blob allTheStuff;
abstract void somethingElse() = 0;
void doAllTheWork() {
for (w : workerList) {
w->workOn(allTheStuff);
}
}
};
class B_Blob : public Blob {
int moreData[4096];
};
class BulbasaurTrainingCamp : public Abstract {
B_Blob allTheStuff;
void somethingElse() {} // implemented
// this class will accept Bulbasaurs into workerList
};
class Bulbasaur : Worker {
Bulbasaur(): name("Fushigidane") {}
void workOn(Blob& b) {
// bulbasaurs cover *all* their workspace with crap
for (int i=0; i<sizeof(b.data[0])/sizeof(b.data); ++i) {
b.data[i] = *((int*)&("crap"));
}
for (i=0; i<sizeof(b.moreData[0])/sizeof(b.moreData); ++i) {
b.moreData[i] = *((int*)&("crap"));
}
}
Here, the abstract bas class has a Blob, but the instance of BulbasaurTrainingCamp has a derived B_Blob. It appears that since I gave it the same name, the compiler accepts it.
Is there a name for this? What I want to know is what the behavior is when I do this. Have I overridden the Blob with the B_Blob?
I am basically not sure about whether there is an inaccessible base Blob instance hanging around inside of BulbasaurTrainingCamp. My expectation is that each Bulbasaur will write 16512 (not 16384) bytes of crap across the two member variables of B_Blob. I am hoping that C++ will actually do what appears to be the sensible thing. It's a case of, "it compiles so I think I should be happy, but I'm still not totally sure it's doing what I think it should be doing".
#include<iostream>
#include<vector>
using namespace std;
int main()
{
class base
{
public:
int sameName;
base(int x):sameName(x){}
};
class derived : public base
{
public:
int diffName;
int sameName;
derived(int x,int i,int j):base(x),diffName(i),sameName(j){}
};
derived example(1,2,3);
cout<<example.sameName<<endl;
cout<<example.diffName<<endl;
cout<<example.base::sameName<<endl;
}
The result is 3 2 1.
I hope the example could be helpful.
A base class, even an abstract one, will be included in its entirety within any derived classes. The new allTheStuff name hides the old one, but does not suppress its inclusion; the base class version can still be accessed using Abstract::allTheStuff. Worse, the function doAllTheWork will end up accessing the base class allTheStuff because it can't possibly know there's an identically-named member variable in a subclass.
If you want this kind of behaviour, you have a few decent options:
Don't put any meaningful code or data in the base class; leave it as a pure interface. This may result in code duplication (but you may be able to factor it out into new base classes or shared helper functions).
Use a dynamically sizable container type as the Blob, so you can dynamically ask for more or less space in the constructor.
Make Blob a separate inheritance hierarchy (e.g. B_Blob and S_Blob inherit from an abstract Blob with differing amounts of space allocated), with a virtual function in Abstract that returns the Blob to use.
You seem to be somehow assuming that this code compiles using C++. It certainly doesn't. Even after patching about various of the C++/CLI specifics, it remains that a Blob does not have a data member called moreData and the only way to get at it (using C++) is to use a suitable cast.
The BulbasaurTrainingCamp objects will have two members called allTheStuff, one of type Blob and one of type B_Blob. Which one you get depends on which type you are looking at (since all members are private, you won't get any, but let's ignore that detail) and/or which qualification you use:
BulbasaurTrainignCamp btc;
B_Blob& b_blob = bts.allTheStuff;
Blob& blob1 = bts.Abstract::allTheStuff;
Abstract& abstract;
Blob& blob2 = abstract.allTheStuff;
That is, when using something which looks like a BulbasaurTrainingCamp you can access both the Blob and the B_Blob objects but you need to use qualification to access Abstracts allTheStuff member. When using an Abstract you can only access Abstracts Blob object.

How can I use a void* argument in C++ for multiple object types?

In short, I have multiple classes that I have created for representing data from different devices (cameras, actually). They both have different behavior under the hood, but the interaction is built to be the exact same from the outside. I am trying to write a utility function that can work with either class, or presumably any more classes I write, so long as the interaction is the same. I'm pretty new to C++, so bear with me if my terminology is not exactly right.
So lets say I have these definitions for each camera.
class CamDataA
{
int getImageStart() {return ptrToStart;)
int getImageSize() {return imageSizeVariable;)
};
class CamDataB
{
int getImageStart() {return ptrToStart;)
int getImageSize() {return width*height*channels;)
};
And I want to have another separate class that can work interchangeably with either class
class imageUtils
{
//constructors/destructors
int reportSize( void* camData)
{
cout << camData->getImageSize();
}
};
But the error I get when compiling is:
error: ‘void*’ is not a pointer-to-object type
Is this even possible?
void * is an untyped pointer. To call a method of an object via pointer, the pointer must be of the appropriate type. You can explicitly cast your void * to CamDataA* or CamDataB* if you know what object it points to, but that's not what you want (you don't know the type of an object beforehand).
In your case, it's nice to use virtual methods.
1) Define an interface. I.e. define a set of methods without implementation.
class CamDataBase {
public:
virtual int getImageStart() = 0; // "=0" means abstract methods - MUST be
virtual int getImageSize() = 0; // overriden in descendants
};
The keyword virtual means that the method can be overridden in descendant classes. This means that if we have a pointer, say CamDataBase* p, and the pointer points to some descendant class, e.g. p = new CamDataA(), and if we write p->getImageStart(), then there will be a call of method that corresponds real (current) type of object (CamDataA::getImageStart()), not CamDataBase::getImageStart(), although p is a pointer to CamDataBase.
2) Now define a couple of implementations of the interface. Methods that have the same signature as virtual methods in a parent class override them.
class CamDataA: public CamDataBase {
int getImageStart() {return ptrToStart;)
int getImageSize() {return imageSizeVariable;)
};
class CamDataB: public CamDataBase {
int getImageStart() {return ptrToStart;)
int getImageSize() {return width*height*channels;)
};
3) Now define a function that accepts a pointer to CamDataBase or any of its descendants:
void reportSize(CamDataBase* camData) // using the base class
{
// type of the object and the appropriate method
// are determined at run-time because getImageSize() is virtual
std::cout << camData->getImageSize();
}
And here are several examples:
CamDataA A;
CamDataB B;
reportSize(&A); // CamDataA::getImageSize() is called
reportSize(&B); // CamDataB::getImageSize() is called
CamDataBase *p = &A;
reportSize(p); // CamDataA::getImageSize() is called
// and even if we cast pointer to CamDataA* to a pointer to CamDataB*:
reportSize((CamDataB*)&A); // CamDataA::getImageSize() is called
I hope you'll search the Web for all the words that are new to you. :)
Seems the second function is lower case whereas you defied it as upper case, and you didn't cast it to a particular object. ((CamDataA*)camData)->getImageSize...
However that is not the way to do it in C++, I would suggest you read a little more about Object Oriented...as doing the cast and using void* is very C like syntax.
With Object Oriented you can have type checking (as you can pass anything to void*) and they provide more structure and clarity to your program.
C++ (and other object oriented langauges) use Base class as a contract, that says all objects of this type should have these functions (method), so for example a base class of bag defines a method of PutItemInBag and then backpack, suitcase, handbag, etc all inherit from bag and each can have a different implementation of PutItemInBag and handle it differently, as this way outside object can handle all bags the same without having to worry which object it is, or if there is a new type of object in the system.
This is done via virtual methods - Virtual Method Overview
Then you can make the base class abstract by having an abstract virtual method
(making it = 0 in C++). This means this method has no implementation and you cannot create objects of this type. This class is only an interface (or contract) and methods that inherit from it should override this method and give their own implementation.
Abstract Classes
What you need is to have both class have a abstract base class and handle it that way..
class BaseCamData
{
virtual int getImageSize() = 0;
};
//then have both class inherit form it.
class CamDataA : public BaseCamData
{
virtual int getImageSize () {return 50;/*imagesize*/}
}
class CamDataB : public BaseCamData
{
virtual int getImageSize () {return 70;/*imagesize*/}
}
int reportSize(BaseCamData* camData)
{
count << camData->getImageSize();
}
}

Can I assign a member data pointer to a derived type?

This is probably best shown with example code. The following fails to compile with g++:
struct Base {
};
struct Derived : public Base {
};
struct Container {
Derived data_;
};
int main(void) {
Base Container::*ptr = &Container::data_;
}
I get the following error: invalid conversion from 'Derived Container::*' to Base Container::*'.
Is this not allowed by the language? Is this a compiler bug? Am I using the wrong syntax?
Please help!
Some background as to why I'm trying to do this: I have several member data pieces that I want to use primarily as their derived types, but I want to be able to populate them through some common code. Data will be coming in an arbitrary order and have a string label that I would use to select the appropriate member data to populate. I was planning on creating a std::map<std::string, Base Container::*> to assign data to each member through a common interface. I'd like to avoid have a giant if else construct to find the right member data.
This is not a compiler bug, you can't do that. (But you can assign a Base::* to a Derived::*).
I don't see any good reason for the limitation (excepted that to handle the case of multiple inheritance, that would complicate even more the representation of a member pointer).
There are a lot of fairly complex, some not-well-explained, and a few flat wrong answers in this thread.
But the problem, it seems to me, is that there simply isn't a Base member within Container -- there is a Derived member. You can't do this:
Base Container::*ptr = &Container::data_;
...for the same reason you can't do this:
int a;
long* pl = &a;
In the second example, the object isn't a long, it's an int. Similarly, in the first example the object isn't a Base, it's a Derived.
As a possibly tangential point, it seems to me like what you really want to do is have Base be an abstract class, and have Container have a Base* rather than a Derived member.
Pointers to members in C++ are not really pointers but more like offsets to given member and are specific to the type, so what you are trying to do is not really supported.
Here's a decent discussion here on Stackoverflow C++: Pointer to class data member.
You just need to write:
Base* ptr = &container.data_;
but container has to be an instance of Container, so you have to create one variable of that type somewhere.
You cannot convert C::*A to C::*B even if there is a conversion possible between A and B.
However, you can do this:
struct Base
{
virtual ~Base() {}
virtual void foo() { std::cout << "Base::foo()\n"; }
};
struct Derived : Base
{
void foo() { std::cout << "Derived::foo()\n"; }
};
struct Bar
{
Base* x;
Bar() : x(new Derived) {}
};
int main()
{
Bar b;
Base* Bar::*p = &Bar::x;
(b.*p)->foo();
}
You would have to static_cast to do this conversion as seen in 5.3.9/9. This reason for this is that it acts as a static_cast from parent object pointer to child object pointer would. In other words, putting a pointer to a derived member into a pointer-to-parent-member would allow you to possibly access a non-existent derived member from a parent object or pointer. If the standard allowed this automatically it would be easy to mess up and try to access a child member on a class that isn't of the appropriate child type (that contains said member).
Without more information it sounds like you need a different/better constructor/set interface in your Base class rather than trying to use pointers-to-member here.
I think what you want is a 'container', ie a struct which just has pointers:
struct Container{
Base* derivedAdata_;
Base* derivedBdata_;
...
};
Now each of the members you know to be of a specific type (ie DerivedA, DerivedB etc) so you can down-cast them later.
But first you are receiving data (in arbitrary order), but with a string name, so you should have a map:
std::map<std::string, Base* Container::*>
And you must have already populated the map:
myMap["DerivedA"] = &Container::derivedAdata;
...
Now data arrives and you start populating the container:
instance.*(myMap[key]) = factory(key, data);
myMap[key] picks the right member of the container and factory(key,data) creates instances.
btw you could just have a map as your container anyway:std::map<std::string, Base*>
Regarding the original issue, you can do this using pointer to functions, instead of introducing base classes.
class Container {
public:
void set(std::string const& label, std::string const& value);
void setName(std::string const& value) { _name = value; }
void setAge(std::string const& age) {
_age = boost::lexical_cast<size_t>(age);
}
private:
std::string _name;
size_t _age;
};
How to implement set then ?
// container.cpp
typedef void (Container::*SetterType)(std::string const&);
typedef std::map<std::string, SetterType> SettersMapType;
SettersMapType SettersMap =
boost::assign::map_list_of("name", &Container::setName)
("age", &Container::setAge);
void Container::set(std::string const& label, std::string const& value) {
SettersMapType::const_iterator it = SettersMap.find(label);
if (it == SettersMap.end()) { throw UnknownLabel(label); }
SetterType setter = it->second;
(this->*setter)(value);
}
struct Container {
Derived data_;
};
int main(void)
{
Base Container::*ptr = &Container::data_;
}
The first problem is that Container doesn't have a member called ptr
Container container_object;
Base *ptr = container_object.data_;
Would work. Note that there needs to be a container object to create the data_ member and it would need to be made public.
The alternative would be for derived::data_ to be a static member.

Downcasting a pointer using a function instead of giant if statement

I have a vector with pointers of type Vehicle. Vehicle is the base class and there are many derived types like MotorCycle, Car, Plane, etc. Now, in my program there comes a point where I need the derived type while traversing the vector. Each Vehicle class has a GetType() function which returns an int which tells me what the derived type is (motorcylce, car, plan). So, I can use a dynamic cast to downcast to the derived type from the base class pointer. However, I need to have a giant if statement everytime I need the derived pointer
if(vehicle_ptr->GetType() == PLANE)
Plane *ptr = dynamic_cast<Plane*> vehicle_ptr;
else if (vehicle_ptr->GetType() == MOTORCYCLE)
MotorCycle *ptr = dynamic_cast<MotorCycle*> vehicle_ptr;
..and on and on.
Is there a way to have a function or some trick I can call that would save me from the giant if statement everywhere? Like ::GetDerivedPtr(Vehicle *ptr). Would a template class help here? (never used them before) Sorry, my C++ is a bit rusty and I did search but these terms bring up too much material to find what I'm looking for. Thanks.
It looks like you've manually tried to recreate polymorphism. You don't need a type member. This is almost always a bad idea. Use polymorphism and virtual functions.
When you have a vehicle pointer v and do
v->function();
It will call the proper function for whatever type (Plane, Train, or Automobile) that the pointer actually points to if function is a virtual function. What you're doing is already handled by the language.
So:
class A {
public:
virtual void f() {cout << "A";}
};
class B : public A {
public:
virtual void f() {cout << "B";}
};
int main(){
A *a;
B b;
a = &b;
a->f();
}
The above snippet will print B.
I second the idea that you need some virtual function and a common base type. Imagine that there is some way to get the pointer which has the correct type. What will you do with it then? You'll have to make a giant switch anyway, because you call specific functions for each of your specific types.
One solution would be to invent a name for the operation you are trying to execute, and put its implementation as a virtual function at each specific Vehicle class. If the operation accepts different parameter for each of the cases, the parameters have to be packed into a special polymorphic structure/class, but here maybe the Visitor pattern is a more generic solution.
First check whether what you're going to do can be done simply via virtual functions in class Vehicle, overridden by each derived class.
If not, then consider the Visitor Pattern.
Cheers & hth.,
dynamic_cast will check the type itself (you don't need your own variable for this). You can do the following instead:
Plane *plane_ptr = dynamic_cast<Plane*>(vehicle_ptr);
if(plane_ptr != NULL)
{
// Do stuff with 'plane_ptr' that you couldn't do with 'vehicle_ptr'
}
I don't really see how creating a function to do the cast would help because you still need to class specific code anyway (and the function would have a fixed return type, so the closest you could get is something like the 'dynamic_cast' call, which is pretty much a standard function anyway).
Use Visitor based dispatching. Observe that not a simple cast of any kind is required in the follwing (somewhat trivialized) example:
// simple cyclic visitor
class VehicleVistor {
public:
// add overload for each concrete Vehicle type
virtual void Visit(class Motorcycle&) {};
virtual void Visit(class Plane&) {};
virtual void Visit(class Car&) {};
};
class Vehicle {
public:
virtual Accept(VehicleVisitor&) = 0;
};
class Car : public Vehicle {
public:
virtual Accept(VehicleVisitor& pVisitor) {
pVisitor.Visit(*this);
}
};
// and so on...
At some point of you program you need to retrieve all instances of, say Motorcycle:
class MotorcycleExtractingVisitor : public VehicleVisitor {
std::vector<Motorcycle*> mMotorcycles;
public:
void operator()(Vehicle* pVehicle) {
pVehicle->Accept(*this);
}
void Visit(Motorcycle& pMotorcycle) {
mAllMotorcycles.push_back(pMotorcycle);
}
std::vector<Motorcycles*> Get() { return mAllMotorcycles; }
};
class Extractor {
public:
// here you extract motorcycles
static std::vector<Motorcycle*> ExtractMotorcycles(std::vector<Vehicle*>& pVehicles) {
MotorcycleExtractingVisitor tMotos;
std::for_each(pVehicles.begin(), pVehicles.end(), tMotos);
return tMotos.Get();
}
// this would be a templatized version, left as exercise to the reader
template<class TExtracted, classtypename TBegItr, typename TEndItr>
static std::vector<TExtracted*> Extract(TBegItr pBeg, TEndItr pEnd) {
ExtractingVisitor<TExtracted> tRequiredVehicles;
std::for_each(pBeg, pEnd, tRequiredVehicles);
return tRequiredVehicles.Get();
}
};
Usage is as follows:
// fixed type version:
std::vector<Motorcycles*> tMotos =
Extractor::Extract(tVehicleVector);
// templatized version (recommended)
std::vector<Motorcycles*> tMotos =
Extractor::Extract<Motorcycles>(
tVehicleVector.begin(),tVehicleVector.end());