3 May 2025 · 5 min
In C++, templates enable generic programming by allowing functions and classes to operate on different data types without sacrificing type safety. Defined using the template keyword, they let developers write reusable, type-agnostic code, such as functions (e.g., template <typename T> max(T a, T b)) or classes (e.g., std::vector), where the type T is specified at compile time.
Historically, the C++ language has tended to produce complicated compiler error messages. The main culprit is template metaprogramming. C++ templates are powerful but complex. When errors occur in template code, the compiler generates long, verbose messages with nested type information, often involving deep template instantiations. A simple mistake in a template function can produce a message spanning multiple lines with obscure type names.
Let us consider an example. In C++, we often use the ‘Standard Template Library (STL)’. It includes a useful dynamic array template: std::vector. A vector manages a sequence of elements with automatic memory handling and flexible sizing. Unlike fixed-size arrays, it can grow or shrink at runtime through operations like push_back to append elements or pop_back to remove them. You can store just about anything in an std::vector but there are some limits. For example, your type must be copyable.
Let us create a C++ type that is not copyable:
struct non_copyable { non_copyable() = default; non_copyable(const non_copyable&) = delete; // No copy };
If we try to create an empty std::vector with non_copyable, it might seemingly work:
std::vector<non_copyable> v;
However, once you try to actually work with the std::vector instance, you may get verbose error messages. Let me write a vectorize function template takes a single value of any type and returns a std::vector containing that value as its sole element. If I try to call this vectorize function template with my non_copyable type, I get in trouble:
template <typename type> std::vector<type> vectorize(type&& t) { return {t}; } void g() { non_copyable m; // works: std::vector<non_copyable> v; // fails: vectorize(m); }
It does not work simply because the compiler tries to copy a non_copyable instance. It is not difficult error. Yet the compiler error message can be epic. For example, you might get the following error:
include/c++/16.0.0//bits/allocator.h:133:30: note: in instantiation of template class 'std::__new_allocator' requested here
| class allocator : public __allocator_base<_Tp>
| ^
include/c++/16.0.0/ext/alloc_traits.h:46:47: note: in instantiation of template class 'std::allocator' requested here
| template
| ^
include/c++/16.0.0/bits/stl_vector.h:93:35: note: in instantiation of default argument for '__alloc_traits<std::allocator>' required here
| typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template
| ^~~~~~~~~~~~~~~~~~~~~~
include/c++/16.0.0/bits/stl_vector.h:458:30: note: in instantiation of template class 'std::_Vector_base>' requested here
| class vector : protected _Vector_base<_Tp, _Alloc>
| ^
:50:5: note: in instantiation of template class 'std::vector' requested here
| vectorize(m);
C++ concepts, introduced in C++20, are a compile-time mechanism for defining and enforcing constraints on template parameters. Using the concept keyword, developers can specify requirements that a type must satisfy to be used with a template, such as having certain operations, member functions, or inheriting from a specific base class. Concepts improve error messages by catching type mismatches early and make code more expressive by documenting intent. They can be applied directly in template declarations (e.g., template).
In our case, we can define a type that can be used in an std::vector instance: we require the type to be destructible, copyable, and default constructible.
template <typename T> concept vector_element = requires(T a, T b) { // Must be destructible requires std::destructible<T>; // Must be copy constructible requires std::copy_constructible<T>; // Must be copy assignable requires std::assignable_from<T&, T>; // Must be default constructible (for operations like resize) requires std::default_initializable<T>; };
Concepts in C++20 are general. For example, if I wanted to require that an instance can be compared with itself, I might define the following concept:
template<typename T> concept equality_comparable = requires(T a, T b) { { a == b } -> std::convertible_to<bool>; };
You can similarly define a concept for a type like std::vector that supports a ‘push_back’ method.
template<typename T> concept pushable = requires(T a, typename T::value_type val) { { a.push_back(val) }; };
In any case, let me now write a new vectorize function with my newly defined vector_element concept:
template <vector_element type> std::vector<type> safe_vectorize(type&& t) { return {t}; }
And this time, you are going to get a much better error message when writing the following erroneous code:
void g() { non_copyable m; safe_vectorize(m); }
For example, you may get the following error:
error: no matching function for call to 'safe_vectorize' note: candidate template ignored: constraints not satisfied [with type = non_copyable &] note: because 'non_copyable &' does not satisfy 'vector_element'
C++ templates, while powerful for enabling generic and reusable code, often lead to complex and verbose error messages, particularly when misused, as seen with the std::vector and non_copyable example. The introduction of C++20 concepts allows developers to enforce type constraints explicitly, resulting in clearer, more concise error diagnostics. By using concepts like vector_element, programmers can catch errors early and improve code readability.
The adoption of C++20 has been excellent, both by compiler vendors and by major users. If you can, I recommend you take C++ concepts out for a spin.
Daniel Lemire, "C++20 concepts for nicer compiler errors," in Daniel Lemire's blog, May 3, 2025, https://lemire.me/blog/2025/05/03/c20-concepts-for-nicer-compiler-errors/.
[BibTeX]
It’s very helpful
It’s helpful for beginners
I feel like concepts are a symptom of a larger issue in the language. I’m not entirely sure what that is, but if we are only using concepts to obtain “nicer” compiler errors, I think that smells. I’ve usually spent more time writing concepts than I have debugging compiler errors when I don’t use concepts.
Exactly my thoughts…
Dusted off my C++ skills after a long time with Java and later Kotlin, but always curious about the huge developments since C++0x, I’m really impressed with the advanced in the language and standard library but the horrible error messages are still there like 20 years ago 😅
I think adding concepts is like adding type checking to a language that has been previously untyped. This can be painful, because you have to figure out all the type constraints, but ultimately beneficial.
It’s not about generating nicer error messages alone. It also helps communicate intent, can make templates more readable, prevent unintended errors by people substituting incorrect arguments that happen to have a compatible interface, can improve compiler performance by eliminating candidates earlier, and so on.
I can’t find the right compiler options to autovectorize this fast Walsh Hadamard tranform code in c:
#include
#include
#include
void h8(float* vec,float scale,uint32_t n){
for(uint32_t i=0;i<n;i+=8){
float a=vec[i]*scale;
float b=vec[i+1]*scale;
float c=vec[i+2]*scale;
float d=vec[i+3]*scale;
float h0=a+b+c+d;
float h1=a-b+c-d;
float h2=a+b-c-d;
float h3=a-b-c+d;
a=vec[i+4]*scale;
b=vec[i+5]*scale;
c=vec[i+6]*scale;
d=vec[i+7]*scale;
float g0=a+b+c+d;
float g1=a-b+c-d;
float g2=a+b-c-d;
float g3=a-b-c+d;
vec[i]=h0+g0;
vec[i+1]=h1+g1;
vec[i+2]=h2+g2;
vec[i+3]=h3+g3;
vec[i+4]=h0-g0;
vec[i+5]=h1-g1;
vec[i+6]=h2-g2;
vec[i+7]=h3-g3;
}
}
void wht8(float* vec,uint32_t n){
uint32_t hs = 8;
while(hs<n){
uint32_t i=0;
while(i<n){
uint32_t j = i + hs;
while(i<j){
float a = vec[i];
float b = vec[i + hs];
vec[i] = a + b;
vec[i + hs] = a – b;
i += 1;
}
i += hs;
}
hs += hs;
}
}
void wht(float* vec,uint32_t n)
{
h8(vec,1.0f,n);
wht8(vec,n);
}
int main()
{
float x[65536];
for(uint32_t i=0;i<65536;i++) x[i]=0.0f;
//x[0]=1.1f;
// Calculate the time taken by fun()
clock_t t;
t = clock();
for(uint32_t i=0;i<1000;i++){
wht(x,65536); }
t = clock() – t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
printf("wht() took %f seconds to execute per 1000\n", time_taken);
printf("%f per second\n", 1000.0/time_taken);
// printf("%f", x[0]);
return 0;
}
It only gives 220 transforms per second on my computer.
I know it can be autovectorized to give 3500 per second because when coded in FreeBasic which emits c as a intermediate during compile that is what I get. Also with Java I get 1400 per second.
O3 is not working for me.
https://archive.org/details/mini-java-collection
https://archive.org/details/switch-net_202406
Did you accidentally add this comment to the wrong post? It doesn’t seem relevant to C++ concepts.
Also, whatever was the argument of your “#include” statements was swallowed up, probably because it was in between angle brackets.
My experience on real projects is that you end up with a nice message into … 2000 lines of template slop instantiation, such that the user experience has not all improved with that regards.