The Legend of C++: Learn me if you can

This is my forth and last year in university studying to get bachelor’s degree in software engineering. Since the first year (2009) I’ve introduced to C++ Programming Language. Since year three (fall 2011) I was teaching C++ new students as a teacher assistant. Though sometimes I feel I’ve never learned even a bit of C++ ! I never stopped studying, coding but every day I learn a new, surprising fact about the language.

"Learn Me if You Can" Poster :D

“Learn Me if You Can” Poster 😀

The last interesting feature of C++ I learned today, is called surrogate call functions. That is the simple fact:

Template arguments can be callable objects or function pointers

After a short WTF moment, I realized that the feature is extremely useful. Then I passed a little longer “Why didn’t i think of that?” moment. Finally my mind get addicted to the subject. I can’t wait to use it in my codes 🙂

template<typename FT1, typename FT2>
class callable_object {
  FT1 *f1;
  FT2 *f2;

public:
  callable_object(FT1 *_f1, FT2 *_f2):f1(_f1), f2(_f2) { }
  operator FT1*() { return f1; }
  operator FT2*() { return f2; }
};

void f(const int& i){ /* do something useful */ }
void g(const double& d){ /* do something useful */ }

int main() {
  callable_object<void(const int&), void(const double&)> c(foo, bar);
  c(10);   // ==> f
  c(10.0); // ==> g
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s