C++ specific patterns due to language design
c++, design-patterns, garbage-collection
Solution
I really love trait classes. Not exactly specific of C++ (other languages as Scala have them), but it allows you to adapt objects, basically to specify a set of operations that a type should support. Imagine that you want a "hasher", in the sense of `tr1::hash`. hash is defined for some types, but not for others. How can you make a class that has a hash defined for all the types that you want? You can declare a class such as:
template < typename T>
struct hashing_tratis
{
typedef std::tr1::hash<T> hashing_type;
};
that is, you expect a class that has the correct hasing_type defined to be used. However, hash is not defined, say, for `myType`, so you can write:
template <>
struct hashing_traits<myType>
{
typedef class_that_knows_how_to_hash_myType hashing_type;
};
This way, suppose that you need a way to hash any type that you use in your program (including `myType`). You can write an "universal" hasher by creating a hasing trait:
template <typename T>
struct something {
typename hashing_traits<T>::hashing_type hasher;
.... // here hasher is defined for all your relevant types, and knows how to hash them
Problem
It took me a long time to realize how important and subtle having variables that: 1) exist on the stack 2) have their destructors called when they fall out of scope are. These two things allow things like: A) RAII B) refcounted GC Interesting enough, (1) & (2) are not available in "lower" languages like C/Assembly; nor in "higher" languages like Ruby/Python/Java (since GC prevents predictable destruction of objects). I'm curious -- what other techniques do you know of that are very C++ specific, due to language design choices. Thanks! Edit: If your answer is "this works in C++ & this other langauge", that's okay too. The things I want to learn about are similar to: By choosing to not have certain features (like GC), we gain other features (like RAII + predicable destructing of objects). In what areas of C++, by choosing to NOT have features that other "higher level" langauges have, C++ manages to get patterns that those higher level langauges can't express.