C++ Lookup table for derived classes - c++

I have a wrapper class holding a bunch of derived class objects by means of a vector of references to a common base class. During runtime, the Child objects are created based on user input.
#include <iostream>
#include <vector>
#include <memory>
#include <type_traits>
class Base {
public:
virtual void run() = 0;
};
class Wrapper {
public:
std::vector<std::shared_ptr<Base>> blocks;
template <class Child>
auto create() -> std::shared_ptr<Child>
{
auto block = std::make_shared < Child > ();
blocks.emplace_back(block);
return std::move(block);
}
template <typename A, typename B>
void connect(A a, B b)
{
using connectionType = typename A::element_type::out;
connectionType* port = new connectionType;
a.get()->ptr_out = port;
b.get()->ptr_in = port;
}
};
class Child_1 : public Base {
public:
using in = int;
using out = float;
out* ptr_out;
in* ptr_in;
void run() { std::cout<<"running child 1\n"; *ptr_out = 1.234;};
};
class Child_2 : public Base {
public:
using in = float;
using out = bool;
out* ptr_out;
in* ptr_in;
void run() { std::cout<<"running child 2\ngot: "<<*ptr_in; };
};
int main () {
Wrapper wrapper;
/* read config file with a list of strings of which types to create */
std::vector < std::string > userInput;
userInput.push_back("Type 0");
userInput.push_back("Type 1");
for (auto input:userInput)
{
if (input == "Type 0")
wrapper.create < Child_1 > ();
else if (input == "Type 1")
wrapper.create < Child_2 > ();
/* and so on */
}
/* read config file with a list of pairs of which objects to connect */
std::vector < std::pair < int, int >>connections;
connections.push_back(std::make_pair(0, 1));
// e.g. user wants to connect object 0 with object 1:
for (int i = 0; i < connections.size (); i++)
{
auto id0 = connections[i].first; // e.g. 0
auto id1 = connections[i].second; //e.g. 1
// this will not work because Base has no typename in / out:
// wrapper.connect (wrapper.blocks[id0], wrapper.blocks[id1]);
// workaround:
wrapper.connect(
std::dynamic_pointer_cast<Child_1>(wrapper.blocks[id0]),
std::dynamic_pointer_cast<Child_2>(wrapper.blocks[id1]));
}
wrapper.blocks[0].get()->run();
wrapper.blocks[1].get()->run();
return 0;
}
Now, I'm only able to store a vector of Base objects which cannot hold the different in/out types of each derived object. When I want to connect the derived objects (which are stored as Base class objects), I need to dynamic_pointer_cast them back into their derived class. What's the most efficient way to do this?
There are a few ways I could think of - none of which seem to be possible (to my knowledge) with C++:
Have some kind of lookup-table / enum which returns a type to cast to; I could then create a map from the user input "Type 0" etc to the type and cast accordingly.
Have some kind of lambda-like expression that would return the correctly casted pointer type such that I can call wrapper.connect( lambda_expression(...), lambda_expression(...) ).
Brute force: check for each possible combination of user inputs and call the connect function with the dynamic_pointer_cast (as shown in the coding example). This will very likely not be suitable for my real-world application (currently using about 25 such classes) because it would result in a huge number of not maintainable function calls...
Somehow give the generic in/out types to the Base class but I can't think of any method to do so.
I really hope I'm missing something obvious. Any help is much appreciated.

This looks like a typical case of double dynamic dispatching, however there is a possible simplification in that the output and input types must match. Hence, here is sort of a half-Visitor pattern.
First, we extract the concepts of input and output types into classes so that they can be targeted by dynamic_cast:
template <class In_>
struct BaseInput {
using In = In_;
std::shared_ptr<In> ptr_in;
};
template <class Out_>
struct BaseOutput {
using Out = Out_;
std::shared_ptr<Out> ptr_out;
};
Note: I've swapped in std::shared_ptrs rather than letting raw owning pointers in the wild.
From there, we can declare a virtual connectTo function in Base to get the first level of dynamic dispatching:
class Base {
public:
virtual ~Base() = default;
virtual void run() = 0;
virtual void connectTo(Base &other) = 0;
};
Note: I have added a virtual destructor to Base. AFAICT it is superfluous thanks to std::shared_ptr's type erasure, however Clang was spewing warnings at me and I wasn't willing to chase them down.
Finally, the second dynamic lookup can be done from Base::connectTo's override, which I have factored out in a handy template:
template <class In, class Out>
struct Child
: Base
, BaseInput<In>
, BaseOutput<Out> {
void connectTo(Base &other_) override {
// Throws std::bad_cast if other_'s input type doesn't match our output type
auto &other = dynamic_cast<BaseInput<Out> &>(other_);
this->ptr_out = other.ptr_in = std::make_shared<Out>();
}
};
At that point a Visitor pattern would swap the objects around and perform a second virtual call from other_ to get the second dynamic dispatch. However, as mentioned above, we know exactly what type we're looking for, so we can just dynamic_cast to reach it.
Now we can implement Wrapper::connect as simply:
template < typename A, typename B > void connect (A a, B b)
{
a.get()->connectTo(*b.get());
}
... and define child classes this way:
class Child_1 : public Child<int, float> {
public:
void run() { std::cout<<"running child 1\n"; *ptr_out = 1.234;};
};
See it live on Wandbox

Related

C++ Errors declaring Interface with return template

I have a base interface, declaration like this - IBaseTest.h:
#pragma once
template <class T1>
class IBaseTest
{
public:
virtual ~IBaseTest();
virtual T1 DoSomething() = 0;
};
And two children who overrides DoSomething() CBaseTest1 claass in - BaseTest1.h:
#pragma once
#include "IBaseTest.h"
class CBaseTest1: public IBaseTest<int>
{
public:
virtual int DoSomething();
};
BaseTest1.cpp:
#include "BaseTest1.h"
int CBaseTest1::DoSomething()
{
return -1;
}
And CBaseTest2 in - BaseTest2.h
#pragma once
#include "IBaseTest.h"
class CBaseTest2: public IBaseTest<long long>
{
public:
virtual long long DoSomething();
};
BaseTest2.cpp:
#include "BaseTest2.h"
long long CBaseTest2::DoSomething()
{
return -2;
}
So CBaseTest1::DoSomething() overrides return type to int, and CBaseTest2::DoSomething() to long long. Now, i want to use a pointer to the base interface, to work with those classes, and there i have the problem:
#include "IBaseTest.h"
#include "BaseTest1.h"
#include "BaseTest2.h"
int _tmain(int argc, _TCHAR* argv[])
{
IBaseTest<T1> * pBase = NULL;
pBase = new CBaseTest1();
cout << pBase->DoSomething() << endl;
pBase = new CBaseTest2();
cout << pBase->DoSomething() << endl;
getchar();
return 0;
}
The problem is i cannot declare IBaseTest<T1> * pBase = NULL; T1 is undefined. If declare the template before _tmain like this:
template <class T1>
int _tmain(int argc, _TCHAR* argv[])
{
...
}
I get: error C2988: unrecognizable template declaration/definition
So what do i put here instead of T1?
IBaseTest<??> * pBase = NULL;
The problem is that T1 parameter needs to be known when you instantiate an object of the template class IBaseTest. Technically, IBaseTest<int> and IBaseTest<long long> are two different types without a common base and C++ does not allow you to declare a variable IBaseTest<T1> pBase = NULL; where T1 is determined at runtime. What you are trying to achieve is something that would be possible in a dynamically typed language, but not in C++ because it is statically typed.
However, if you know the expected return type of DoSomething whenever you call that method, you can sort of make your example to work. First, you need to introduce a common base class that is not a template:
#include <typeinfo>
#include <typeindex>
#include <assert.h>
class IDynamicBase {
public:
virtual std::type_index type() const = 0;
virtual void doSomethingVoid(void* output) = 0;
template <typename T>
T doSomething() {
assert(type() == typeid(T));
T result;
doSomethingVoid(&result);
return result;
}
virtual ~IDynamicBase() {}
};
Note that it has a template method called doSomething that takes a type parameter for the return value. This is the method that we will call later.
Now, modify your previous IBaseTest to extend IDynamicBase:
template <class T1>
class IBaseTest : public IDynamicBase
{
public:
std::type_index type() const {return typeid(T1);}
void doSomethingVoid(void* output) {
*(reinterpret_cast<T1*>(output)) = DoSomething();
}
virtual T1 DoSomething() = 0;
virtual ~IBaseTest() {}
};
You don't need to change CBaseTest1 or CBaseTest2.
Finally, you can now write the code in your main function like this:
IDynamicBase* pBase = nullptr;
pBase = new CBaseTest1();
std::cout << pBase->doSomething<int>() << std::endl;
pBase = new CBaseTest2();
std::cout << pBase->doSomething<long long>() << std::endl;
Note that instead of calling pBase->DoSomething(), we now call pBase->doSomething<T>() where T is a type that must be known statically where we call the method and we provide that type at the call site, e.g. pBase->doSomething<int>().
The language does not allows to do directly what you are trying to do. At that point, you should ask yourself if that is the right solution for the problem.
The first approach that might work well assuming that you don't have too much different operations to do for each type would be to simply do the action in the function itself instead of returning type that are not related through inheritance.
class IBaseTest
{
public:
virtual void OutputTo(std::ostream &os) = 0;
};
class CBaseTest1
{
public:
virtual void OutputTo(std::ostream &os) override;
private:
int DoSomething();
};
void CBaseTest1OutputTo(std::ostream &os)
{
os << DoSomething() << std::endl;
}
If you have only a few types but a lot of operation, you might use the visitor pattern instead.
If you mainly have operation that depends on type, you could use:
class IVisitor
{
public:
virtual void Visit(int value) = 0;
virtual void Visit(long value) = 0;
};
Otherwise, use that which is more general
class IVisitor
{
public:
virtual void Visit (CBaseTest1 &test1) = 0;
virtual void Visit (CBaseTest2 &test2) = 0;
};
Then in your classes add an apply function
class IBaseTest
{
public:
virtual void Apply(IVisitor &visitor) = 0;
};
In each derived class, you implement the Apply function:
void CBaseTest1 : public IBaseTest
{
virtual void Apply(IVisitor &visitor) override
{
visitor.Visit(this->DoSomething()); // If you use first IVisitor definition
visitor.Visit(*this); // If you use second definition
};
And for creation purpose, you could have a factory that return the appropriate class from a type tag if you need to create those class from say a file…
One example assuming you want a new object each time:
enum class TypeTag { Integer = 1, LongInteger = 2 };
std::unique_ptr<IBaseTest> MakeObjectForTypeTag(TypeTag typeTag)
{
switch (typeTag)
{
case TypeTag::Integer : return new CBaseTest1();
case TypeTag::LongInteger : return new CBaseTest2();
}
}
So the only time you would do a switch statement is when you are creating an object… You could also use a map or even an array for that...
The right approach depends on your actual problem.
How many CBaseClass* do you have?
Do you expect to add other classes? Often?
How many operations similar to DoSomething() do you have?
How many actions that works on the result of DoSomething do you have?
Do you expect to add other actions? Often?
By responding to those questions, it will be much easier to take the right decision. If the action are stables (and you only have a few one), then specific virtual functions like OutputToabove is more appropriate. But if you have dozen of operation but don't expect much changes to ITestBase class hierarchy, then visitor solution is more appropriate.
And the reason why a given solution is more appropriate in a given context is mainly the maintenance effort when adding classes or actions in the future. You typically want that the most frequent change (adding a class or an action) require les changes everywhere in the code.

How to store different objects in an array and get an object of a certain type?

You may have heard of the Entity Component System, where everything is an Entity and each entity has a list of Components which control its functionality.
I am trying to find out how to store different objects (each inherit Component) in an array and be able to get an object out of that array based on their type.
The first solution I can think of would be to have an enum for the types of objects inheriting component:
enum ComponentType : unsigned char // There will never be more than 256 components
{
EXAMPLE_COMPONENT,
ANOTHER_EXAMPLE_COMPONENT,
AND_ANOTHER_EXAMPLE_COMPONENT
};
Then Component base class has a ComponentType type; with a getter, and each child component sets its type e.g:
ExampleComponent::ExampleComponent()
{
type = EXAMPLE_COMPONENT;
}
And then I'd have a GetComponent function:
Component* Entity::GetComponent(ComponentType type)
{
for (unsigned int i = 0; i < m_components.size(); i++)
{
if (m_components.at(i).GetType() == type)
{
return &m_components.at(i);
}
}
return nullptr;
}
// Note: m_components is an std::vector;
And then finally you would call GetComponent e.g:
(ExampleComponent*) component = entity.GetComponent(EXAMPLE_COMPONENT);
The problem with this is that you need an enum for each type of component and you also have to cast the component after using GetComponent to make sure you can access its own member variables.
Does anyone know of a proper way of doing this where there is no need for an enum and there is no need to cast the component? If there is a solution that still requires a type variable to be stored in each component it preferably would be a byte and can't be any bigger than 4 bytes.
Edit: I also don't want to use templates
Thanks in advance!
David
Your approach simulates polymorphism: Having the type as a member and an if statement checking for that type is typically a indication to make use of a class hierarchy. You already stated that you want to use objects derived from the Componenttype, so you should also make proper use of polymorphism.
The second problem in your approach is that you want to filter for a "specific type", which more or less is equivalent to a downcast — i.e. a dynamic_cast<>(): When you pass a certain ComponentType to Entity::GetComponent(), it returns a pointer to Component, but the object behind that pointer is always an object of a specific derived class: In your example you always get an ExampleComponent object, when you pass EXAMPLE_COMPONENT to that function.
The following question arises then naturally: What do you want to do with the object returned by this function? You can only call methods from the Component interface/class, but no method from the derived class! So the downcast hardly makes sense at all (it would, if you would return a pointer to an object of a class derived from Component.
Here is how it looks like using polymorphism and with the downcast in the getComponent() method, returning a pointer to a derived class — note that the method is a template to conveniently implement this for every class derived from Component:
#include <string>
#include <vector>
#include <iostream>
class Component {
public:
virtual std::string getType() = 0;
};
using ComponentContainer = std::vector<Component*>;
class AComponent : public Component { public: virtual std::string getType() { return "A"; }; };
class BComponent : public Component { public: virtual std::string getType() { return "B"; }; };
class CComponent : public Component { public: virtual std::string getType() { return "C"; }; };
class Entity {
public:
template <typename T>
T* getComponent();
void putComponent(Component* c) { m_components.push_back(c); }
private:
ComponentContainer m_components;
};
template<typename T>
T* Entity::getComponent()
{
T* t = nullptr;
for (auto i : m_components) {
if ((t = dynamic_cast<T*>(i)) != nullptr)
break;
}
return t;
}
int main()
{
Entity e;
e.putComponent(new AComponent{});
e.putComponent(new BComponent{});
Component* c;
if ((c = e.getComponent<AComponent>()) != nullptr)
std::cout << c->getType() << std::endl;
// delete all the stuff
return 0;
}
The heavy use of dynamic_cast<>() is problematic both from performance and from design point of view: It should only be used rarely, if ever.
So the design problem may be that everything is stored in a single container? You could instead use several containers, based on "behaviour". As behaviour is implemented in an ECS as a derived class or interface, a getComponent()-similar method of this entity would only return objects of certain (sub-)interfaces. These components would then all implement a given interface method, so the need for down-casting would be eliminated.
For example, given you have "drawable components", this suggests the hierarchy:
// Drawable interface
class DrawableComponent : public Component {
public:
virtual void draw() const = 0;
};
// Drawable objects derive from DrawableComponent
class DComponent : public DrawableComponent {
public:
virtual void draw() const { /* draw the D component */ }
};
Then, an entity could have a container of DrawableComponent objects and you would just iterate over those objects and call draw() on each:
using DrawableContainer = std::vector<DrawableComponent*>;
// m_drawables is a memober of Entity with above type
const DrawableContainer& Entity::getDrawables() { return m_drawables; }
// then just draw those objects
for (auto d : entity.getDrawables())
d->draw(); // no downcast!

Overwrite Base Class Member with New Type

I'm trying to use C++ to emulate something like dynamic typing. I'm approaching the problem with inherited classes. For example, a function could be defined as
BaseClass* myFunction(int what) {
if (what == 1) {
return new DerivedClass1();
} else if (what == 2) {
return new DerivedClass2();
}
}
The base class and each derived class would have the same members, but of different types. For example, BaseClass may have int xyz = 0 (denoting nothing), DerivedClass1 might have double xyz = 123.456, and DerivedClass2 might have bool xyz = true. Then, I could create functions that returned one type but in reality returned several different types. The problem is, when ere I try to do this, I always access the base class's version of xyz. I've tried using pointers (void* for the base, and "correct" ones for the derived classes), but then every time I want to access the member, I have to do something like *(double*)(obj->xyz) which ends up being very messy and unreadable.
Here's an outline of my code:
#include <iostream>
using std::cout;
using std::endl;
class Foo {
public:
Foo() {};
void* member;
};
class Bar : public Foo {
public:
Bar() {
member = new double(123.456); // Make member a double
};
};
int main(int argc, char* args[]) {
Foo* obj = new Bar;
cout << *(double*)(obj->member);
return 0;
};
I guess what I'm trying to ask is, is this "good" coding practice? If not, is there a different approach to functions that return multiple types or accept multiple types?
That is not actually the way to do it.
There are two typical ways to implement something akin to dynamic typing in C++:
the Object-Oriented way: a class hierarchy and the Visitor pattern
the Functional-Programming way: a tagged union
The latter is rather simple using boost::variant, the former is well documented on the web. I would personally recommend boost::variant to start with.
If you want to go down the full dynamic typing road, then things get trickier. In dynamic typing, an object is generally represented as a dictionary containing both other objects and functions, and a function takes a list/dictionary of objects and returns a list/dictionary of objects. Modelling it in C++ is feasible, but it'll be wordy...
How is an object represented in a dynamically typed language ?
The more generic representation is for the language to represent an object as both a set of values (usually named) and a set of methods (named as well). A simplified representation looks like:
struct Object {
using ObjectPtr = std::shared_ptr<Object>;
using ObjectList = std::vector<ObjectPtr>;
using Method = std::function<ObjectList(ObjectList const&)>;
std::map<std::string, ObjectPtr> values;
std::map<std::string, Method> methods;
};
If we take Python as an example, we realize we are missing a couple things:
We cannot implement getattr for example, because ObjectPtr is a different type from Method
This is a recursive implementation, but without the basis: we are lacking innate types (typically Bool, Integer, String, ...)
Dealing with the first issue is relatively easy, we transform our object to be able to become callable:
class Object {
public:
using ObjectPtr = std::shared_ptr<Object>;
using ObjectList = std::vector<ObjectPtr>;
using Method = std::function<ObjectList(ObjectList const&)>;
virtual ~Object() {}
//
// Attributes
//
virtual bool hasattr(std::string const& name) {
throw std::runtime_error("hasattr not implemented");
}
virtual ObjectPtr getattr(std::string const&) {
throw std::runtime_error("gettattr not implemented");
}
virtual void setattr(std::string const&, ObjectPtr) {
throw std::runtime_error("settattr not implemented");
}
//
// Callable
//
virtual ObjectList call(ObjectList const&) {
throw std::runtime_error("call not implemented");
}
virtual void setcall(Method) {
throw std::runtime_error("setcall not implemented");
}
}; // class Object
class GenericObject: public Object {
public:
//
// Attributes
//
virtual bool hasattr(std::string const& name) override {
return values.count(name) > 0;
}
virtual ObjectPtr getattr(std::string const& name) override {
auto const it = values.find(name);
if (it == values.end) {
throw std::runtime_error("Unknown attribute");
}
return it->second;
}
virtual void setattr(std::string const& name, ObjectPtr object) override {
values[name] = std::move(object);
}
//
// Callable
//
virtual ObjectList call(ObjectList const& arguments) override {
if (not method) { throw std::runtime_error("call not implemented"); }
return method(arguments);
}
virtual void setcall(Method m) {
method = std::move(m);
}
private:
std::map<std::string, ObjectPtr> values;
Method method;
}; // class GenericObject
And dealing with the second issue requires seeding the recursion:
class BoolObject final: public Object {
public:
static BoolObject const True = BoolObject{true};
static BoolObject const False = BoolObject{false};
bool value;
}; // class BoolObject
class IntegerObject final: public Object {
public:
int value;
}; // class IntegerObject
class StringObject final: public Object {
public:
std::string value;
}; // class StringObject
And now you need to add capabilities, such as value comparison.
You can try the following design:
#include <iostream>
using std::cout;
using std::endl;
template<typename T>
class Foo {
public:
Foo() {};
virtual T& member() = 0;
};
class Bar : public Foo<double> {
public:
Bar() : member_(123.456) {
};
virtual double& member() { return member_; }
private:
double member_;
};
int main(int argc, char* args[]) {
Foo<double>* obj = new Bar;
cout << obj->member();
return 0;
};
But as a consequence the Foo class already needs to be specialized and isn't a container for any type anymore.
Other ways to do so, are e.g. using a boost::any in the base class
If you need a dynamic solution you should stick to using void* and size or boost::any. Also you need to pass around some type information as integer code or string so that you can decode the actual type of the content.
See also property design pattern.
For example, you can have a look at zeromq socket options https://github.com/zeromq/libzmq/blob/master/src/options.cpp

C++ template specify type by Enum

I'm facing a problem :
I want to create a function which calls a specific template type constructor depending on a enum that the function will receive. By that i mean :
typedef ____ (Class<whatever>::*tabType)(int flag);
template<typename T>
static Class* Class<t>::createClassInstance(enum precision)
{
static const ___ createTab[] = {
Class<int>,
Class<double>
}
return (new createTab[precision](1));
}
There are a number of ways of achieving this sort of thing, but it sounds like you want to create an array (or map) of factory methods (one for each class), indexed by the enum variable. Each one calls the relevant constructor, and returns a new object of that type.
Of course, for this to make any sense, all of the classes must derive from a common base.
If the enum value is dynamic as a function argument, you'll have to use either a dispatch table or switch/if-else. Notice that your pseudo code does not clearly explain the requirement. Say, what exactly the createInstance function you wish to define and how is it going to be called?
I would say, just construct a std::map that maps the enum to a factory function (boost::function<>). Then you just add one entry for each type that you want, with its corresponding enum. To actually construct the factory functions. You can either have some static Create() function for each class and store a function pointer. Or, you can use Boost.Lambda constructor/destructor functors. Or, you can use Boost.Bind to construct functors that wrap a factory function that requires some number of parameters. Here is an example:
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/lambda/construct.hpp>
#include <map>
struct Base { };
struct Derived1 : public Base { };
struct Derived2 : public Base {
static Base* Create() { return new Derived2; };
};
struct Derived3 : public Base {
int value;
Derived3(int aValue) : value(aValue) { };
static Base* Create(int aValue) { return new Derived3(aValue); };
};
enum DerivedCreate { ClassDerived1, ClassDerived2, ClassDerived3 };
int main() {
std::map< DerivedCreate, boost::function< Base*() > constructor_map;
constructor_map[ClassDerived1] = boost::lambda::new_ptr<Derived1>();
constructor_map[ClassDerived2] = &Derived2::Create;
constructor_map[ClassDerived3] = boost::bind(&Derived3::Create, 42);
//now you can call any constructor as so:
Base* ptr = constructor_map[ClassDerived2]();
};
I might have made some slight syntax mistakes, but basically you should be able make the above work. Also, the fact that you have several class templates plays no role, once they are instantiated to a concrete class (like Class<int> or Class<double>) they are just like any other class, and the above idea should remain valid.
Extending your example, something like the following works:
enum Prec {INT, DOUBLE};
struct Base
{
virtual ~Base () = 0 {}
};
template<typename T> struct Class : public Base
{
static Base* create (int flag) {return new Class<T> (flag);}
Class (int flag) {}
};
typedef Base* (*Creator) (int flag);
Base* createClassInstance (Prec prec)
{
static const Creator createTab[] = {
Class<int>::create,
Class<double>::create
};
return createTab[prec] (1);
}
int main (int argc, char* argv[])
{
Base* c = createClassInstance (DOUBLE);
return 0;
}

Technique for Using Templates and Virtual Functions

A while back I learned about the Curiously Recurring Template Pattern (http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern), and it reminded me of a technique I had used to implement an event queue cache.
The basic idea is that we take advantage of a Base class pointer to store a container of homogeneous pointer types. However because the Derived class is a template class, which stores an item of type T, what we are really storing is a list of heterogeneous types.
I was curious if anyone has seen this technique, which is perhaps interesting, and if so if anyone has named it? Anyone care to critique it? Is there a better way to achieve my end here?
Thanks.
#include <iostream>
#include <algorithm>
#include <functional>
#include <list>
#include <string>
class Base
{
public:
Base(){}
virtual ~Base(){}
virtual void operator()() = 0;
};
template<typename C, typename T>
class Derived : public Base
{
public:
Derived(C* c, T item) : consumer_(c), item_(item) {}
virtual void operator()()
{
consumer_->consume(item_);
}
C* consumer_;
T item_;
};
class Consumer
{
bool postpone_;
std::list<Base*> cache_;
public:
Consumer() : postpone_(true)
{
}
void pause()
{
postpone_ = true;
}
void resume()
{
postpone_ = false;
const std::list<Base*>::iterator end = cache_.end();
for ( std::list<Base*>::iterator iter = cache_.begin();
iter != end;
++iter )
{
Base* bPtr = *iter;
bPtr->operator()();
delete bPtr;
}
cache_.clear();
}
void consume(int i)
{
if ( postpone_ )
{
std::cerr << "Postpone int.\n";
cache_.push_back(new Derived<Consumer, int>(this, i));
}
else
{
std::cerr << "Got int.\n";
}
}
void consume(double d)
{
if ( postpone_ )
{
std::cerr << "Postpone double.\n";
cache_.push_back(new Derived<Consumer, double>(this, d));
}
else
{
std::cerr << "Got double.\n";
}
}
void consume(char c)
{
if ( postpone_ )
{
std::cerr << "Postpone char.\n";
cache_.push_back(new Derived<Consumer, char>(this, c));
}
else
{
std::cerr << "Got char.\n";
}
}
};
static Consumer consumer;
void destroy(Base* object)
{
delete object;
}
int main()
{
// Consumer is registered with something that sends events out to lots
// of different consumer types (think observer pattern). Also in the non-toy
// version consumer isn't being passed PODs, but various Event types.
consumer.consume(0);
consumer.consume(0.1f);
consumer.consume('x');
consumer.resume();
}
The output is:
Postpone int.
Postpone double.
Postpone char.
Got int.
Got double.
Got char.
What you are using is plain polymorphism, as Stephen points out in his comment. While you store different objects internally in the container, you are limited to using the interface defined in Base. That is, of course, unless you intend to add type checking and downcasts to actually retrieve the values. There is just a limited amount of things that you can do with unrelated objects.
Depending on what you are actually wanting to achieve you might consider using other solutions like boost::any/boost::variant if what you want is to actually store unrelated types (in the few cases where this makes sense --cells in a spreadsheet, for example).
anyone has named it?
I think it is an adapter pattern implemented without using inheritance from T.
Anyone care to critique it?
YOu could have used short template function instead of this class. Or you could use template function that returns template class. Template function can automatically guess required types - sou you could omit <> and do less typing.
Nice.
You're utilizing compiler's power to generate templated series of derived classes and it's actually cool that you can mix plain derived classes
(written by yourself) with template-specialized derived classes and with compiler-generated ones
(built as result of template instantiation).
class Base { ... };
template <typename Y> class Derived1 : public Base { ... };
template <specialization>
class Derived1 : public Base { ... };
class Derived2 : public Base { ... };
This could be useful, but it doesn't somehow extend the polymorphism term, because you're still limited to the Base class interface.
Also, you could write a plain factory which would have some templated method for generating subclasses and use it to avoid writing new Derived1<std::string>..., but write something like
std::string a;
Base* base = Factory.Create(a)