Checking whether a class has a member function with a given signature

When writing template code, being able to detect whether a type has a method with a given signature may be very useful. For example, when writing a custom buffer, checking for T::size() may allow us to preallocate memory in an input function. Checking for T::operator bool() will tell us whether our type is testable without writing specializations for every such type, which would be especially tedious for unnamed types. (side note: lambdas don’t have operator bool(), but they’re implicitly convertible to function pointers when their capture list is empty, which should make them testable, but they aren’t in VC 10 and 11)

Achieving the desired result requires basic understanding of SFINAE and overload resolution. Let’s say we want to check for existence of ::size() as used in the standard library or in the codebase of Qt, that is size_t (T::*)() const and int (T::*)() const respectively.

Right angle brackets and backwards compatibility

Ever since introduction of C++03 the standard committee set out to fix many minor annoyances in the language (auto, ranged for and initializer lists to name a few). Most of those are new things that cannot change the behaviour of existing code, but there are, of course, exceptions. In C++03 the first line of the following code was ill-formed, because >> was parsed as operator>>.

std::vector<std::vector<int>>  X; // ill-formed
std::vector<std::vector<int> > Y; // ok

Parentheses that change everything

It is well known — and intuitively understood by most — that adding a set of parentheses usually doesn’t change anything; for example, int answer = 42; is equal to int answer = (42); or int answer = ((42));. There are some important exceptions to that rule, however, and I’ll talk about these in this post.

Macros

Although macros are rarely used in good C++ code, it is important to be able to understand what’s happening and why. Using a popular example of MIN macro, the naïve implementation would look like this:

#define MIN(x,y) x < y ? x : y

To a beginner, this would look like a correct implementation, and indeed, it would work in some cases; for example, answer below would indeed be equal to 42:

int answer = MIN(42,50);

Unfortunately, macros are expanded as text, and in the following example, possibly surprisingly, answer would hold the value of 41 instead:

int answer = 2 + MIN(40,41);