This is the first in a series of articles on writing crossplatform applications with C++. These articles will be based on the premise that strict adherence to standard C++ will result in extremely portable code which will run on almost every platform available, including embedded systems.
However, limiting yourself to strict C++ also means limiting yourself to the standard C++ libraries, which only cover basic file and console input and output. That means no graphical user interfaces.
On occasion you will read or hear someone talking about C++ templates causing code bloat. I was thinking about it the other day and thought to myself, "self, if the code does exactly the same thing then the compiled code cannot really be any bigger, can it?"
Here are the test cases presented, first without the use of templates, second with the use of templates. Exactly the same functionality and exactly the same code output:
Standard Algorithms
Few C++ developers seem to appreciate that the standard C++ library is actually designed around functional programming principles. The standard library headers algorithm and functional header files provide functional algorithms and facilitate their use, respectively.
As usual we will try to provide a simple example of why we should put to use the functional techniques in the standard library.
We've covered the "Assembly Language", "C" and "C++" of the C++ threading world, and now we are going to try and move beyond that.
In the "C++" example we showed a object that automatically managed a thread's life time and used the thread to calculate the Fibonacci sequence in the background. Using templates we should be able to make a generic version of the Fibonacci calculator thread.
C++ templates is a huge topic that we will not fully cover here. While we have covered templates in the past, this article will cover the very basics and the reasons why we would want to use templates.
A simple case of why you would want to understand templates is wrapped up in a question I used to ask when I would interview C++ developer candidates, "write for me a max() function which can compare any two values of the same type."
If boost::threads represent the C of multithreaded programming, then RAII and automatically managed threads represent the C++ of multithreaded programming.
In the last article we promised that using more RAII would allow us to get this code even smaller and better to manage. Here is the result of that:
class threaded_class
{
public:
threaded_class()
: m_stoprequested(false),
m_thread(boost::bind(&threaded_class::do_work, this)) //Note 2
{
}
~threaded_class()
{
Recent comments
3 days 20 hours ago
3 days 22 hours ago
3 days 22 hours ago
6 days 23 hours ago
1 week 5 min ago
1 week 3 days ago
2 weeks 3 days ago
5 weeks 3 days ago
7 weeks 55 min ago
8 weeks 2 days ago