Pass by iterator is not a new concept, but one that we are going to perhaps give a new name to today and propose as a standard for normal usage.
If you take for example the normal way of passing around standard containers:
// Print a vector of strings separated by spaces.
void print(const std::vector<std::string> &t_vector)
{
for(std::vector<std::string>::const_iterator itr = t_vector.begin();
itr != t_vector.end();
++itr)
{
std::cout << *itr << " ";
}
}
std::vector<std::string> m_vec;
m_vec.push_back("Hello");
m_vec.push_back("World");
print(m_vec);The idea of "Pass By Iterator" that we are proposing involves never again writing code like the above.
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:
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.
In my last posting about C++ Multiple Dispatch I wondered if it was really any different than function overloading. I now appreciate that it is something that needs to occur at runtime, not compile time. With a little help from the Boost libraries, I threw together this example of how one could do Multiple Dispatch in C++.
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."
A while back I was going though the first chapters of Knuth's The Art of Computer Programming and came across Euclid's algorithm for finding the greatest common denominator. I decided to implement the algorithm as a C++ template. Here's the complete example.
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