syntax highlight

Tuesday, 17 May 2011

Cool C++0X features VI: A variadic wrapper

Let's work on the last variadic exercise, a wrapper. Say you have something like this:

#include <iostream>

void do_something() { std::cout << __PRETTY_FUNCTION__ << "n"; }

int main() {
	do_something();
	return 0;
}

And you want to wrap do_something with something else (Remember __PRETTY_FUNCTION__?). This is a solution, the worst one though (or, to be accurate, the most boring one):

#include <iostream>

void do_something() { std::cout << __PRETTY_FUNCTION__ << "n"; }

void wrap() { 
	std::cout << __PRETTY_FUNCTION__ << "n";
	do_something();
}

int main() {
	wrap();
	return 0;
}

Why is it so bad? Let's say you don't control do_something, you just control the wrapper. You may not even control main(), it may be beyond your scope. That means each time do_something changes, or adds an overload, you have to change your code. That's ugly and you should already know how to set up a variadic function to forward the arguments to do_something. Give it a try, next time the solution.

No comments:

Post a Comment