Creating new object with parameter - c++

void ChangeState(int newState)
{
nextState = newState;
//Change the state
switch( nextState ) ///the change still will have a case for everything
{
case STATE_INTRO:
{
vec.pop_back();
state ptr(new CIntroState);
vec.push_back(ptr);
break;
}
case STATE_MENU:
{
vec.pop_back();
state ptr(new CMainMState);
vec.push_back(ptr);
break;
}
}
}
I have this function that allows me to change my current state; however, I thought about it and this is going to be a huge switch statement by the time I am finished. Currently, it already has about 10 states in it, this is just some sample code. I am trying to do something a little different, but I am not sure how to go about it.
void ChangeState(something)
{
vec.pop_back();
state ptr(new something);
vec.push_back(ptr)
}
If I could bring it in this way, I could completely avoid the use of the switch statement and get the same end result. Does anyone know how to go about this? Any help would be greatly appreciated.

You need to link compile-time polymorphism (i.e., templates) and run-time polymorphism, as ryanbwork suggests. The challenge here is to try to avoid transforming your current form of repetitive code (the big switch) into a similarly verbose but more declarative form of repetitive code.
As another popular Stack Overflow question reveals, clone methods are usually the way one creates new instances of dynamically determined types at run-time. Cloning is really a specialization of the more general factory pattern, and you could create a set of factories for your types whose definition would be only a little more verbose than your current enumeration presumably is:
template <class T>
class factory {
public:
T* operator()() {return new T;}
};
factory<CIntroState> IntroState;
factory<CMainState> MainState;
// etc...
template <class Fac>
void ChangeState(Fac newStateFactory)
{
vec.pop_back();
vec.push_back(newStateFactory());
}

It looks like you need a combination of templates and polymorphism. With templates, you don't need to enumerate all the different types that you may pass into a function, as this will be done for you during compilation. To store all of these different types in the same vector, you'll need to have them all sub class some super-type which then allows you to store them side by side in a vector of super-type.

Related

Object-oriented jump table defined over multiple classes

I am in the midst of refactoring a NMOS6502 emulator into multiple classes. I was wondering if there is an "object-oriented" way to define a function jump table. Basically, I have defined separate instruction classes to classify groups of related cpu operations- like "CStackInstHandler" or "CArithmeticInstHandler" which will have a reference to a cpu object. Each instruction class is derived from an abstract instruction class. Each derived instruction class has a set of functions which will use the cpu object's public interface to change the cpu state e.g:
uint8_t opcode = _memory->readMem(_cpu->getProgramCounter());
AInstructionHandler* _handler = _cpu->getInstHandler(opcode);
_handler->setCpu(&cpu);
_handler->setMemory(&memory);
_handler->execute(opcode);
The problem is that at runtime an instruction handler as well as the appropriate member function defined for that handler needs to be determined using an opcode.
So we have - opcode is read from memory, a table is used by the cpu to map opcode to instruction handler type, and then the same opcode is used by the instruction handler to select the correct function. Each instruction overrides an "execute" function e.g:
void CBranchInstHandler::execute() {
switch(_opcode) {
case 0x90:
this->BCC();
break;
case 0xb0:
this->BCS();
break;
case 0xf0:
this->BEQ();
break;
case 0x30:
this->BMI();
break;
case 0xd0:
this->BNE();
break;
case 0x10:
this->BPL();
break;
default:
break;
}
}
void CBranchInstHandler::BCC() {
uint16_t address = this->getAddress();
if(!_cpu->isCarry()) {
uint16_t pc = _cpu->getPC();
pc += address;
_cpu->setPC(pc);
}
}
/*more instruction specific functions...*/
I end up with two look-ups, one of which is redundant. One to select the handler, and another to select the handler function. I feel like this is the wrong way to accomplish this task, but I am not sure of an alternative that doesn't just devolve into groups of non-member functions.
I am wondering if anyone has insight into this problem. It basically boils down to wanting to refactor a class into smaller bites (cpu class with instruction member functions refactored to cpu class and instruction classes), but the all of the components are so interrelated that I end up having to repeat myself. Redundancy is introduced.
A non-object oriented solution would be to just have these instructions be non-member functions that accept a cpu reference. Then, a function jump table would be defined, instructions would be looked up and indexed by opcode and executed.
This doesn't really seem practical with objects. I could make all the instructions static or something but this seems to miss the point.
Any insight or information about even tangentially related problems would be super helpful.
Thanks.
I'm going to promote my comment to an answer: the object-oriented solution is, as you say, to give the child classes full responsibility for deciding which opcodes they respond to.
I'd suggest that the easiest way of doing that isn't to try to build a two-stage switch but simply to route every opcode to every child and let the child either contribute or not. That's the minimum viable solution.
If you need an optimisation then the easiest thing would be to reformulate:
void CBranchInstHandler::execute() {
switch(_opcode) {
case 0x90:
this->BCC();
break;
... etc ...
}
}
To:
FuncPtr CBranchInstHandler::execute() {
switch(_opcode) {
case 0x90:
return BCC;
... etc ...
}
return NULL;
}
So each execute returns whether it in fact handled that opcode.
Within the parent class you could then simply keep a table from opcode to function pointer. An array will do. The table will initially contain NULLs throughout.
When performing an opcode, look up the handler in the table. If the handler is there, call it and move on. If not then call execute on every child in turn until someone that returns a handler, then put them into the table and then call it. So you'll build it just-in-time, at runtime. The first run of each opcode will take slightly longer but you'll subsequently have what amounts to a jump table.
The advantage of that is that it allows the information about what a child handles to be tied closely to the actual handling of it syntactically, reducing code overhead and the probability of error.
If I understand, what you are doing is creating a class for each type of instruction (Branch, Arithmetic, Load, Store, etc) and then within those you are writing member functions for the individual instructions -- c.f. you have a "CBranchInstrHandler" which handles "branch on carry", "branch on zero" etc?
The fully Object Oriented approach is to extend your subclassing down to individual instructions.
class CBranchInstrHandler { virtual void execute() = 0; };
class CBranchOnCarryClear : public CBranchInstrHandler {
void execute() override {
...;
}
};
class CBranchOnCarrySet : public CBranchInstrHandler {
void execute() override {
...;
}
};
Now you can look your instructions up in one shot, but you'll need a one-to-one mapping of all of these.
switch (opCode) {
case 0x90: return .. CBranchOnCarryClear .. ;
case 0xB0: return .. CBranchOnCarrySet .. ;
}
The elipsis are there because I'm not sure how you are getting a pointer to your CBranchInstrHandler; I'm guessing that they are static and that you aren't newing them every instruction.
If they are dataless, you can return them as function objects by value:
struct Base { virtual void execute() { /* noop */ } };
struct Derived { void execute(override) { ... } };
Base getHandler(opcode_t opcode) {
if (opcode == 1) { return Derived(); }
}
but I suspect you probably want to take parameters and store state, in which case return by value here could result in slicing.
Of course, if you are using C++11 you could use lambdas:
switch (opCode) {
case 0x90: return [this] () {
... implement BCC execute here ...
};
case 0xB0: return [this] () {
... implement BCS execute here ...
}
}
You could use pointer to class member function/method:
void (CBranchHandlerBase::*)();
Using for store the pointers to the methods which should be invoked for given _opcode.
map<uint8_t, void (CBranchHandlerBase::*)()> handlers;
handlers[0x90] = &BCC;
handlers[0xb0] = &BCS;
...
The code above should be provided in the initialize section/method inside your base class for the handlers. Of course BCC, BCS and so on must be declared as pure virtual methods to make the approach work.
Then instead of your switch:
void CBranchHandlerBase::execute() {
(this->*handlers[_opcode])();
}
Note that execute is defined in the base class (and it does not have to be virtual! as each Handler will have the same functionality of execute method).
Edit: The map actually can be replaced by the vector or array of size: 2^(8*sizeof(uint8_t)) for efficiency reasons

generic programming in controller for interface between model and view

I am creating a MVC framework for my project in C++. Below is controller source/pseudo code snippet. As you can see, that I have to put explicit check for each type. I have stored type for each property of object(model). Is there a way to avoid this switch case?
for each property P of object:
switch(type of P)
{
case(type_int):
{
int value;
model->fetch(value, P->id);
writer->write(value, P->id);
break;
}
case(type_float):
{
float value;
model->fetch(value, P->id);
writer->write(value, P->id);
break;
}
}
#include<vector>
#include<algorithm>
#include<iostream>
template<typename T>
struct pred{
void operator()(T x)
{
//implemnt algorithm
}
T value;
};
class property{
};
int main()
{
std::vector<property> myShape;
std::for_each(myShape.begin(),myShape.end(), pred<property>());
std::cout<<"Done"<<std::endl;
}
Please use this template function in place of switch
template<typename T>
void func()
{
T value;
model->fetch(value, P->id);
writer->write(value, P->id);
}
Where does value actually come from, because you can use that to drive the generics. As given, there's no way to prevent the switch, because the switch also decides the type of the value. If replace the switch with a variant (assuming you didn't want runtime polymorphism) you can make this work.
The astute reader will note that of course, somewhere internally, a type switch still happens. The essential differences are that
variants can be compile-time optimized away[1], in which case the type switch need not be present in the generated code or is faster
the type switch is hidden, the programmer thinks on a higher abstraction level
That said, if it brings complexity, consider simpler options. This might be premature optimization
[1] in far more (complicated) cases than de-virtualization usually happens

Flexible Data Messaging in a component oriented system

I'm creating a Component orientated system for a small game I'm developing. The basic structure is as follows: Every object in the game is composed of a "GameEntity"; a container holding a vector of pointers to items in the "Component" class.
Components and entities communicate with one another by calling the send method in a component's parent GameEntity class. The send method is a template which has two parameters, a Command (which is an enum which includes instructions such as STEP_TIME and the like), and a data parameter of generic type 'T'. The send function loops through the Component* vector and calls each's component's receive message, which due to the template use conveniently calls the overloaded receive method which corresponds to data type T.
Where the problem comes in however (or rather the inconvenience), is that the Component class is a pure virtual function and will always be extended. Because of the practical limitation of not allowing template functions to be virtualised, I would have to declare a virtual receive function in the header for each and every data type which could conceivably be used by a component. This is not very flexible nor extensible, and moreover at least to me seems to be a violation of the OO programming ethos of not duplicating code unnecessarily.
So my question is, how can I modify the code stubs provided below to make my component orientated object structure as flexible as possible without using a method which violates best coding practises
Here is the pertinent header stubs of each class and an example of in what ways an extended component class might be used, to provide some context for my problem:
Game Entity class:
class Component;
class GameEntity
{
public:
GameEntity(string entityName, int entityID, int layer);
~GameEntity(void){};
//Adds a pointer to a component to the components vector.
void addComponent (Component* component);
void removeComponent(Component*);
//A template to allow values of any type to be passed to components
template<typename T>
void send(Component::Command command,T value){
//Iterates through the vector, calling the receive method for each component
for(std::vector<Component*>::iterator it =components.begin(); it!=components.end();it++){
(*it)->receive(command,value);
}
}
private:
vector <Component*> components;
};
Component Class:
#include "GameEntity.h"
class Component
{
public:
static enum Command{STEP_TIME, TOGGLE_ANTI_ALIAS, REPLACE_SPRITE};
Component(GameEntity* parent)
{this->compParent=parent;};
virtual ~Component (void){};
GameEntity* parent(){
return compParent;
}
void setParent(GameEntity* parent){
this->compParent=parent;
}
virtual void receive(Command command,int value)=0;
virtual void receive(Command command,string value)=0;
virtual void receive(Command command,double value)=0;
virtual void receive(Command command,Sprite value)=0;
//ETC. For each and every data type
private:
GameEntity* compParent;
};
A possible extension of the Component class:
#include "Sprite.h"
#include "Component.h"
class GraphicsComponent: Component{
public:
GraphicsComponent(Sprite sprite, string name, GameEntity* parent);
virtual void receive(Command command, Sprite value){
switch(command){
case REPLACE_SPRITE: this->sprite=value; break
}
}
private:
Spite sprite;
}
Should I use a null pointer and cast it as the appropriate type? This might be feasible as in most cases the type will be known from the command, but again is not very flexible.
This is a perfect case for type erasure!
When template based generic programming and object oriented programming collide, you are left with a simple, but hard to solve problem: how do I store, in a safe way, a variable where I don't care about the type but instead care about how I can use it? Generic programming tends to lead to an explosion of type information, where as object oriented programming depends on very specific types. What is a programmer to do?
In this case, the simplest solution is some sort of container which has a fixed size, can store any variable, and SAFELY retrieve it / query it's type. Luckily, boost has such a type: boost::any.
Now you only need one virtual function:
virtual void receive(Command command,boost::any val)=0;
Each component "knows" what it was sent, and can thus pull out the value, like so:
virtual void receive(Command command, boost::any val)
{
// I take an int!
int foo = any_cast<int>(val);
}
This will either successfully convert the int, or throw an exception. Don't like exceptions? Do a test first:
virtual void receive(Command command, boost::any val)
{
// Am I an int?
if( val.type() == typeid(int) )
{
int foo = any_cast<int>(val);
}
}
"But oh!" you might say, eager to dislike this solution, "I want to send more than one parameter!"
virtual void receive(Command command, boost::any val)
{
if( val.type() == typeid(std::tuple<double, char, std::string>) )
{
auto foo = any_cast< std::tuple<double, char, std::string> >(val);
}
}
"Well", you might ponder, "How do I allow arbitrary types to be passed, like if I want float one time and int another?" And to that, sir, you would be beaten, because that is a Bad Idea. Instead, bundle two entry points to the same internal object:
// Inside Object A
virtual void receive(Command command, boost::any val)
{
if( val.type() == typeid(std::tuple<double, char, std::string>) )
{
auto foo = any_cast< std::tuple<double, char, std::string> >(val);
this->internalObject->CallWithDoubleCharString(foo);
}
}
// Inside Object B
virtual void receive(Command command, boost::any val)
{
if( val.type() == typeid(std::tuple<float, customtype, std::string>) )
{
auto foo = any_cast< std::tuple<float, customtype, std::string> >(val);
this->internalObject->CallWithFloatAndStuff(foo);
}
}
And there you have it. By removing the pesky "interesting" part of the type using boost::any, we can now pass arguments safely and securely.
For more information on type erasure, and on the benefits to erasing the parts of the type on objects you don't need so they mesh better with generic programming, see this article
Another idea, if you love string manipulations, is this:
// Inside Object A
virtual void receive(Command command, unsigned int argc, std::string argv)
{
// Use [boost::program_options][2] or similar to break argv into argc arguments
// Left as exercise for the reader
}
This has a curious elegance to it; programs parse their parameters in the same way, so you could conceptualize the data messaging as running "sub-programs", which then opens up a whole host of metaphors and such that might lead to interesting optimizations, such as threading off parts of the data messaging, etc etc.
However, the cost is high: string operations can be quite expensive compare to a simple cast. Also note that boost::any does not come at zero cost; each any_cast requires RTTI lookups, compared to the zero lookups needed for just passing fixed amounts of parameters. Flexibility and indirection require costs; in this case, it is more than worth it however.
If you wish to avoid any such costs at all, there IS one possibility that gets the necessary flexibility as well as no dependencies, and perhaps even a more palatable syntax. But while it is a standard feature, it can be quite unsafe:
// Inside Object A
virtual void receive(Command command, unsigned int argc, ...)
{
va_list args;
va_start ( args, argc );
your_type var = va_arg ( args, your_type );
// etc
va_end( args );
}
The variable argument feature, used in printf for example, allows you to pass arbitrary many arguments; obviously, you will need to tell the callee function how many arguments passed, so that's provided via argc. Keep in mind, however, that the callee function has no way to tell if the correct parameters were passed; it will happily take whatever you give it and interpret it as if it were correct. So, if you accidentally pass the wrong information, there will be no compile time support to help you figure out what goes wrong. Garbage in, Garbage out.
Also, there area host of things to remember regarding va_list, such as all floats are upconverted to double, structs are passed by pointers (I think), but if your code is correct and precise, there will be no problems and you will have efficiency, lack of dependencies, and ease of use. I would recommend, for most uses, to wrap the va_list and such into a macro:
#define GET_DATAMESSAGE_ONE(ret, type) \
do { va_list args; va_start(args,argc); ret = va_args(args,type); } \
while(0)
And then a version for two args, then one for three. Sadly, a template or inline solution can't be used here, but most data packets will not have more than 1-5 parameters, and most of them will be primitives (almost certainly, though your use case may be different), so designing a few ugly macros to help your users out will deal largely with the unsafety aspect.
I do not recommend this tactic, but it may very well be the fastest and easiest tactic on some platforms, such as ones that do not allow even compile time dependencies or embedded systems, where virtual calls may be unallowed.

Factory method anti-if implementation

I'm applying the Factory design pattern in my C++ project, and below you can see how I am doing it. I try to improve my code by following the "anti-if" campaign, thus want to remove the if statements that I am having. Any idea how can I do it?
typedef std::map<std::string, Chip*> ChipList;
Chip* ChipFactory::createChip(const std::string& type) {
MCList::iterator existing = Chips.find(type);
if (existing != Chips.end()) {
return (existing->second);
}
if (type == "R500") {
return Chips[type] = new ChipR500();
}
if (type == "PIC32F42") {
return Chips[type] = new ChipPIC32F42();
}
if (type == "34HC22") {
return Chips[type] = new Chip34HC22();
}
return 0;
}
I would imagine creating a map, with string as the key, and the constructor (or something to create the object). After that, I can just get the constructor from the map using the type (type are strings) and create my object without any if. (I know I'm being a bit paranoid, but I want to know if it can be done or not.)
You are right, you should use a map from key to creation-function.
In your case it would be
typedef Chip* tCreationFunc();
std::map<std::string, tCreationFunc*> microcontrollers;
for each new chip-drived class ChipXXX add a static function:
static Chip* CreateInstance()
{
return new ChipXXX();
}
and also register this function into the map.
Your factory function should be somethink like this:
Chip* ChipFactory::createChip(std::string& type)
{
ChipList::iterator existing = microcontrollers.find(type);
if (existing != microcontrollers.end())
return existing->second();
return NULL;
}
Note that copy constructor is not needed, as in your example.
The point of the factory is not to get rid of the ifs, but to put them in a separate place of your real business logic code and not to pollute it. It is just a separation of concerns.
If you're desperate, you could write a jump table/clone() combo that would do this job with no if statements.
class Factory {
struct ChipFunctorBase {
virtual Chip* Create();
};
template<typename T> struct CreateChipFunctor : ChipFunctorBase {
Chip* Create() { return new T; }
};
std::unordered_map<std::string, std::unique_ptr<ChipFunctorBase>> jumptable;
Factory() {
jumptable["R500"] = new CreateChipFunctor<ChipR500>();
jumptable["PIC32F42"] = new CreateChipFunctor<ChipPIC32F42>();
jumptable["34HC22"] = new CreateChipFunctor<Chip34HC22>();
}
Chip* CreateNewChip(const std::string& type) {
if(jumptable[type].get())
return jumptable[type]->Create();
else
return null;
}
};
However, this kind of approach only becomes valuable when you have large numbers of different Chip types. For just a few, it's more useful just to write a couple of ifs.
Quick note: I've used std::unordered_map and std::unique_ptr, which may not be part of your STL, depending on how new your compiler is. Replace with std::map/boost::unordered_map, and std::/boost::shared_ptr.
No you cannot get rid of the ifs. the createChip method creats a new instance depending on constant (type name )you pass as argument.
but you may optimaze yuor code a little removing those 2 line out of if statment.
microcontrollers[type] = newController;
return microcontrollers[type];
To answer your question: Yes, you should make a factory with a map to functions that construct the objects you want. The objects constructed should supply and register that function with the factory themselves.
There is some reading on the subject in several other SO questions as well, so I'll let you read that instead of explaining it all here.
Generic factory in C++
Is there a way to instantiate objects from a string holding their class name?
You can have ifs in a factory - just don't have them littered throughout your code.
struct Chip{
};
struct ChipR500 : Chip{};
struct PIC32F42 : Chip{};
struct ChipCreator{
virtual Chip *make() = 0;
};
struct ChipR500Creator : ChipCreator{
Chip *make(){return new ChipR500();}
};
struct PIC32F42Creator : ChipCreator{
Chip *make(){return new PIC32F42();}
};
int main(){
ChipR500Creator m; // client code knows only the factory method interface, not the actuall concrete products
Chip *p = m.make();
}
What you are asking for, essentially, is called Virtual Construction, ie the ability the build an object whose type is only known at runtime.
Of course C++ doesn't allow constructors to be virtual, so this requires a bit of trickery. The common OO-approach is to use the Prototype pattern:
class Chip
{
public:
virtual Chip* clone() const = 0;
};
class ChipA: public Chip
{
public:
virtual ChipA* clone() const { return new ChipA(*this); }
};
And then instantiate a map of these prototypes and use it to build your objects (std::map<std::string,Chip*>). Typically, the map is instantiated as a singleton.
The other approach, as has been illustrated so far, is similar and consists in registering directly methods rather than an object. It might or might not be your personal preference, but it's generally slightly faster (not much, you just avoid a virtual dispatch) and the memory is easier to handle (you don't have to do delete on pointers to functions).
What you should pay attention however is the memory management aspect. You don't want to go leaking so make sure to use RAII idioms.

Where do you find templates useful?

At my workplace, we tend to use iostream, string, vector, map, and the odd algorithm or two. We haven't actually found many situations where template techniques were a best solution to a problem.
What I am looking for here are ideas, and optionally sample code that shows how you used a template technique to create a new solution to a problem that you encountered in real life.
As a bribe, expect an up vote for your answer.
General info on templates:
Templates are useful anytime you need to use the same code but operating on different data types, where the types are known at compile time. And also when you have any kind of container object.
A very common usage is for just about every type of data structure. For example: Singly linked lists, doubly linked lists, trees, tries, hashtables, ...
Another very common usage is for sorting algorithms.
One of the main advantages of using templates is that you can remove code duplication. Code duplication is one of the biggest things you should avoid when programming.
You could implement a function Max as both a macro or a template, but the template implementation would be type safe and therefore better.
And now onto the cool stuff:
Also see template metaprogramming, which is a way of pre-evaluating code at compile-time rather than at run-time. Template metaprogramming has only immutable variables, and therefore its variables cannot change. Because of this template metaprogramming can be seen as a type of functional programming.
Check out this example of template metaprogramming from Wikipedia. It shows how templates can be used to execute code at compile time. Therefore at runtime you have a pre-calculated constant.
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
I've used a lot of template code, mostly in Boost and the STL, but I've seldom had a need to write any.
One of the exceptions, a few years ago, was in a program that manipulated Windows PE-format EXE files. The company wanted to add 64-bit support, but the ExeFile class that I'd written to handle the files only worked with 32-bit ones. The code required to manipulate the 64-bit version was essentially identical, but it needed to use a different address type (64-bit instead of 32-bit), which caused two other data structures to be different as well.
Based on the STL's use of a single template to support both std::string and std::wstring, I decided to try making ExeFile a template, with the differing data structures and the address type as parameters. There were two places where I still had to use #ifdef WIN64 lines (slightly different processing requirements), but it wasn't really difficult to do. We've got full 32- and 64-bit support in that program now, and using the template means that every modification we've done since automatically applies to both versions.
One place that I do use templates to create my own code is to implement policy classes as described by Andrei Alexandrescu in Modern C++ Design. At present I'm working on a project that includes a set of classes that interact with BEA\h\h\h Oracle's Tuxedo TP monitor.
One facility that Tuxedo provides is transactional persistant queues, so I have a class TpQueue that interacts with the queue:
class TpQueue {
public:
void enqueue(...)
void dequeue(...)
...
}
However as the queue is transactional I need to decide what transaction behaviour I want; this could be done seperately outside of the TpQueue class but I think it's more explicit and less error prone if each TpQueue instance has its own policy on transactions. So I have a set of TransactionPolicy classes such as:
class OwnTransaction {
public:
begin(...) // Suspend any open transaction and start a new one
commit(..) // Commit my transaction and resume any suspended one
abort(...)
}
class SharedTransaction {
public:
begin(...) // Join the currently active transaction or start a new one if there isn't one
...
}
And the TpQueue class gets re-written as
template <typename TXNPOLICY = SharedTransaction>
class TpQueue : public TXNPOLICY {
...
}
So inside TpQueue I can call begin(), abort(), commit() as needed but can change the behaviour based on the way I declare the instance:
TpQueue<SharedTransaction> queue1 ;
TpQueue<OwnTransaction> queue2 ;
I used templates (with the help of Boost.Fusion) to achieve type-safe integers for a hypergraph library that I was developing. I have a (hyper)edge ID and a vertex ID both of which are integers. With templates, vertex and hyperedge IDs became different types and using one when the other was expected generated a compile-time error. Saved me a lot of headache that I'd otherwise have with run-time debugging.
Here's one example from a real project. I have getter functions like this:
bool getValue(wxString key, wxString& value);
bool getValue(wxString key, int& value);
bool getValue(wxString key, double& value);
bool getValue(wxString key, bool& value);
bool getValue(wxString key, StorageGranularity& value);
bool getValue(wxString key, std::vector<wxString>& value);
And then a variant with the 'default' value. It returns the value for key if it exists, or default value if it doesn't. Template saved me from having to create 6 new functions myself.
template <typename T>
T get(wxString key, const T& defaultValue)
{
T temp;
if (getValue(key, temp))
return temp;
else
return defaultValue;
}
Templates I regulary consume are a multitude of container classes, boost smart pointers, scopeguards, a few STL algorithms.
Scenarios in which I have written templates:
custom containers
memory management, implementing type safety and CTor/DTor invocation on top of void * allocators
common implementation for overloads wiht different types, e.g.
bool ContainsNan(float * , int)
bool ContainsNan(double *, int)
which both just call a (local, hidden) helper function
template <typename T>
bool ContainsNanT<T>(T * values, int len) { ... actual code goes here } ;
Specific algorithms that are independent of the type, as long as the type has certain properties, e.g. binary serialization.
template <typename T>
void BinStream::Serialize(T & value) { ... }
// to make a type serializable, you need to implement
void SerializeElement(BinStream & strean, Foo & element);
void DeserializeElement(BinStream & stream, Foo & element)
Unlike virtual functions, templates allow more optimizations to take place.
Generally, templates allow to implement one concept or algorithm for a multitude of types, and have the differences resolved already at compile time.
We use COM and accept a pointer to an object that can either implement another interface directly or via [IServiceProvider](http://msdn.microsoft.com/en-us/library/cc678965(VS.85).aspx) this prompted me to create this helper cast-like function.
// Get interface either via QueryInterface of via QueryService
template <class IFace>
CComPtr<IFace> GetIFace(IUnknown* unk)
{
CComQIPtr<IFace> ret = unk; // Try QueryInterface
if (ret == NULL) { // Fallback to QueryService
if(CComQIPtr<IServiceProvider> ser = unk)
ser->QueryService(__uuidof(IFace), __uuidof(IFace), (void**)&ret);
}
return ret;
}
I use templates to specify function object types. I often write code that takes a function object as an argument -- a function to integrate, a function to optimize, etc. -- and I find templates more convenient than inheritance. So my code receiving a function object -- such as an integrator or optimizer -- has a template parameter to specify the kind of function object it operates on.
The obvious reasons (like preventing code-duplication by operating on different data types) aside, there is this really cool pattern that's called policy based design. I have asked a question about policies vs strategies.
Now, what's so nifty about this feature. Consider you are writing an interface for others to use. You know that your interface will be used, because it is a module in its own domain. But you don't know yet how people are going to use it. Policy-based design strengthens your code for future reuse; it makes you independent of data types a particular implementation relies on. The code is just "slurped in". :-)
Traits are per se a wonderful idea. They can attach particular behaviour, data and typedata to a model. Traits allow complete parameterization of all of these three fields. And the best of it, it's a very good way to make code reusable.
I once saw the following code:
void doSomethingGeneric1(SomeClass * c, SomeClass & d)
{
// three lines of code
callFunctionGeneric1(c) ;
// three lines of code
}
repeated ten times:
void doSomethingGeneric2(SomeClass * c, SomeClass & d)
void doSomethingGeneric3(SomeClass * c, SomeClass & d)
void doSomethingGeneric4(SomeClass * c, SomeClass & d)
// Etc
Each function having the same 6 lines of code copy/pasted, and each time calling another function callFunctionGenericX with the same number suffix.
There were no way to refactor the whole thing altogether. So I kept the refactoring local.
I changed the code this way (from memory):
template<typename T>
void doSomethingGenericAnything(SomeClass * c, SomeClass & d, T t)
{
// three lines of code
t(c) ;
// three lines of code
}
And modified the existing code with:
void doSomethingGeneric1(SomeClass * c, SomeClass & d)
{
doSomethingGenericAnything(c, d, callFunctionGeneric1) ;
}
void doSomethingGeneric2(SomeClass * c, SomeClass & d)
{
doSomethingGenericAnything(c, d, callFunctionGeneric2) ;
}
Etc.
This is somewhat highjacking the template thing, but in the end, I guess it's better than play with typedefed function pointers or using macros.
I personally have used the Curiously Recurring Template Pattern as a means of enforcing some form of top-down design and bottom-up implementation. An example would be a specification for a generic handler where certain requirements on both form and interface are enforced on derived types at compile time. It looks something like this:
template <class Derived>
struct handler_base : Derived {
void pre_call() {
// do any universal pre_call handling here
static_cast<Derived *>(this)->pre_call();
};
void post_call(typename Derived::result_type & result) {
static_cast<Derived *>(this)->post_call(result);
// do any universal post_call handling here
};
typename Derived::result_type
operator() (typename Derived::arg_pack const & args) {
pre_call();
typename Derived::result_type temp = static_cast<Derived *>(this)->eval(args);
post_call(temp);
return temp;
};
};
Something like this can be used then to make sure your handlers derive from this template and enforce top-down design and then allow for bottom-up customization:
struct my_handler : handler_base<my_handler> {
typedef int result_type; // required to compile
typedef tuple<int, int> arg_pack; // required to compile
void pre_call(); // required to compile
void post_call(int &); // required to compile
int eval(arg_pack const &); // required to compile
};
This then allows you to have generic polymorphic functions that deal with only handler_base<> derived types:
template <class T, class Arg0, class Arg1>
typename T::result_type
invoke(handler_base<T> & handler, Arg0 const & arg0, Arg1 const & arg1) {
return handler(make_tuple(arg0, arg1));
};
It's already been mentioned that you can use templates as policy classes to do something. I use this a lot.
I also use them, with the help of property maps (see boost site for more information on this), in order to access data in a generic way. This gives the opportunity to change the way you store data, without ever having to change the way you retrieve it.