Tuesday, February 19, 2008

c++: template specification

When you define template class you can't definitely know what type it will wrap:

template<typename T>
class A;
You may use typeid but I don't like it at all. You should use general operations for T. But c++ allows you to define a template class for concrete type:
class A <int>;
Now you have class A for int type. This is rather useful if you can optimize template class for some concrete type.

c++/python: functors as callback with parameters

Almost every more or less serious project uses callbacks. Sometimes programmer wants to pass externally defined arguments to callback function. The way you may chose is to define additional arguments to function that executes callback: c++:

void call(void (*f)(int), int a){f(a);}
void f(int){}
call(f, 1);
def call(f, a):
def f(a):
call(f, 1)
The other way that seemed to me more flexible is to use functors: c++:
template<typename T>void call(T f){f();} 
class A{public: A(int a){} void operator()(){}};
def call(f, a):
class A:
    def __init__(s, a):
    def __call__(s):
Using functors you can use a benefit of 3 calls: constructor, call operator and destructor. But you lose performance and memory. As usual programmer have to deal with (memory/performance/code support) issues =).

Friday, February 15, 2008

c++: namespace alias

Recently found interesting feature in c++: alias to namespace.

namespace A
    int A = 5;

namespace B = A;
I wonder what is it for ... ?