Question

C++ templates are notorious for generating long, unreadable error messages. I have a general idea of why template error messages in C++ are so bad. Essentially, the problem is that the error isn't triggered until the compiler encounters syntax that is not supported by a certain type in a template. For example:

template <class T>
void dosomething(T& x) { x += 5; }

If T doesn't support the += operator, the compiler will generate an error message. And if this happens deep within a library somewhere, the error message might be thousands of lines long.

But C++ templates are essentially just a mechanism for compile-time duck typing. A C++ template error is conceptually very similar to a runtime type error that might occur in a dynamic language like Python. For example, consider the following Python code:

def dosomething(x):
   x.foo()

Here, if x doesn't have a foo() method, the Python interpreter throws an exception, and displays a stack trace along with a pretty clear error message indicating the problem. Even if the error isn't triggered until the interpreter is deep inside some library function, the runtime-error message still isn't anywhere near as bad as the unreadable vomit spewed by a typical C++ compiler. So why can't a C++ compiler be more clear about what went wrong? Why do some C++ template error messages literally cause my console window to scroll for over 5 seconds?

No correct solution

Licensed under: CC-BY-SA with attribution
scroll top