Thursday, June 05, 2008

C++ : std::swap and template specialization

say you want to use the swap method provided in std namespace for your own class . Then instead of using the std::swap option blindly , that would involve making use that your class has at least a copy constructor and that the assignment operator is overridden.

It makes more sense to use template specialization for std::swap

class MyClass {
public:
void Swap(MyClass &) ;
};

namespace std {
template<> swap(MyClass& a, MyClass& b){
a.Swap(b);
}
}

so that way we just tune the default swap to use our class specific Swap and things become fast and simple for us .

Wednesday, June 04, 2008

C++ : std::mem_fun

Say you have a class

class MyClass {
public:
int DoSomething(){
}
};

now say you have

std::vector classes;

you can use something like this

for_each(classes.begin(), classes.end(), &DoSomething);

where DoSomething is

int DoSomething(MyClass& e){
d.DoSomething();
}


to call the member function DoSomething rather than the wrapper function use function calls like these

for_each(classes.begin(), classes.end(), mem_fun_ref(&MyClass::DoSomething));

if the classes vector was defined something like this

vector classes

then you would use something like this

for_each(classes.begin(), classes.end(), mem_fun(&MyClass::DoSomething));

C++ : Template specializations

Assuming you have a piece of code that is templatized and looks like this

template
void prettyPrint(T value, char* buf);

now assume that you are using sprintf for formatting the input .

that being the case you can use template specializations like this :

template<> void prettyPrint(int value, char* buf){
sprintf(buf, "%d", value);
}

template<> void prettyPrint(char value, char* buf){
sprintf(buf, "%c", value);
}

Tuesday, June 03, 2008

C++: copy magic

Say if you have a vector and you want to print it . Then instead of the normal for loop and cout call inside the loop you can do the following :

if you have a vector "v"

copy(v.begin(), v.end(), ostream_iterator(cout, "\n"));

this will print the entire vector .

To generalize this you could use something like this :

template
OutputIterator copy(const Container& c, OutputIterator result){
return std::copy(c.begin(), c.end(), result);
}

C++ : pragma warning

if there is a header file after including which you start getting warnings , and especially if that header file is a third party header file , its better to wrap the header file with your own custom wrapper .

#pragma warning(push)
#pragma warning(disable:line_number_causing_warning)
#include
#pragma warning(pop)