haggholm: (Default)
[personal profile] haggholm

I really enjoyed Effective C++ and stand by what I just said about it. However, the book reminded me not only of joys, but also, it must be admitted, of frustrations.

Let’s look at one last typename Example, because it’s representative of something you’re going to see in real code. Suppose we’re writing a function template that takes an iterator, and we want to make a local copy, temp, of the object the iterator points to. We can do it like this:

template<typename IterT>
void workWithIterator(IterT iter)
{
    typename std::iterator_traits<IterT>::value_type temp(*iter);
    // ...
}

Don’t let the std::iterator_traits<IterT>::value_type startle you. That’s just a use of a standard traits class…

(…And I think that if “typename std::iterator_traits<IterT>::value_type” is “standard”, you should strive to make your standard simpler, cleaner, and more readable…)

…If you think reading std::iterator_traits<IterT>::value_type is unpleasant, imagine what it’s like to type it. If you’re like most programmers, the thought of typing it more than once is ghastly, so you’ll want to create a typedef. […]

template<typename IterT>
void workWithIterator(IterT iter)
{
    typedef typename std::iterator_traits<IterT>::value_type value_type;
    value_type temp(*iter);
    // ...
}

Many programmers find the “typedef typename” juxtaposition initially jarring, but it’s a logical fallout from the rules for referring to nested dependent type names. You’ll get used to it fairly quickly.

With all due respect, Mr. Meyers, I hope never to have to see such monstrosities often enough to get used to them! Some lines of code should just never be written, should never have to be written, and that’s one of them:

typedef typename std::iterator_traits<IterT>::value_type value_type;

In all fairness to Scott Meyers, who’s a very good writer, you do end up having to read and write code like that if you write enough C++ using the ‘right’ parts of the language. I’ve written similar things—and I’ve written things that were not only uglier, but also worse.

My personal opinion is that C++ can be a useful language, but if you are to use it you should strive to avoid this sort of thing in the first place. Personally, I prefer to use Python for expressive power, or C if I need something truly low-level—at least it’s simple. C++ is certainly powerful and expressive, but when that dog starts waving its tentacles at me, my aesthetic sensibilities are offended.

Then again, at least it’s not PHP…

Profile

haggholm: (Default)
Petter Häggholm

July 2025

S M T W T F S
  12 345
6789101112
13141516171819
20212223242526
2728293031  

Most Popular Tags