Generics and templates

Both languages can write one function that adds a slice of numbers without knowing whether the numbers are integers or doubles. C++ has done it with templates since the 1990s and can do far more with them; Go got type parameters in 1.18 and deliberately kept them small. The programs below are the same task, and they are also a good way to see what each language promises at compile time.

A template and a concept

The template is instantiated once per type, so sum<int> and sum<double> are two functions in the binary. The concept says what the template needs from the type, and since C++20 the compiler checks that requirement at the call site.

#include <concepts> #include <iostream> #include <vector> template <typename T> concept Addable = requires(T a, T b) { { a + b } -> std::convertible_to<T>; }; template <Addable T> T sum(const std::vector<T>& values) { T total{}; for (const T& value : values) { total = total + value; } return total; } int main() { std::vector<int> ints{1, 2, 3, 4}; std::vector<double> doubles{0.5, 1.25, 2.0}; std::cout << sum(ints) << "\n"; std::cout << sum(doubles) << "\n"; }

g++ -std=c++23 -O2 -Wall -Wextra concepts.cpp -o concepts
./concepts

10
3.75

Without the concept the same template compiles and fails inside the body when a type does not support +, which is the source of the long error messages C++ was famous for before C++20: the compiler reports the instantiation, the standard library inside it, and the operator that is missing, in that order. The concept moves the check to the signature.

When the type does not fit

A struct with two integers and no operator+ does not satisfy Addable. The compiler still prints a dozen lines, but the first one says the call does not match, and the last line shown says the constraint was not satisfied.

#include <concepts> #include <iostream> #include <vector> struct Point { int x; int y; }; template <typename T> concept Addable = requires(T a, T b) { { a + b } -> std::convertible_to<T>; }; template <Addable T> T sum(const std::vector<T>& values) { T total{}; for (const T& value : values) { total = total + value; } return total; } int main() { std::vector<Point> points{{1, 2}, {3, 4}}; std::cout << sum(points).x << "\n"; }

g++ -std=c++23 -O2 -Wall -Wextra concepts_bad.cpp -o concepts_bad

concepts_bad.cpp: In function 'int main()':
concepts_bad.cpp:28:21: error: no matching function for call to 'sum(std::vector<Point>&)'
28 | std::cout << sum(points).x << "\n";
| ~~~^~~~~~~~
concepts_bad.cpp:28:21: note: there is 1 candidate
concepts_bad.cpp:16:3: note: candidate 1: 'template<class T> requires Addable<T> T sum(const std::vector<T>&)'
16 | T sum(const std::vector<T>& values)
| ^~~
concepts_bad.cpp:16:3: note: template argument deduction/substitution failed:
concepts_bad.cpp:16:3: note: constraints not satisfied

The error names the concept and the call, which is what a beginner needs. What it cannot say is which part of the concept failed, because Addable is a requirement on an expression and the compiler only knows the expression is invalid.

Type parameters and a constraint

A Go constraint is an interface with a type union in it, and ~int means every type whose underlying type is int, including a named type such as type Celsius int. The body is ordinary Go, checked once for every type that satisfies the constraint, not once per instantiation.

package main import "fmt" // Number is the set of types Sum accepts. type Number interface { ~int | ~float64 } // Sum adds the values of the slice. func Sum[T Number](values []T) T { var total T for _, value := range values { total += value } return total } func main() { fmt.Println(Sum([]int{1, 2, 3, 4})) fmt.Println(Sum([]float64{0.5, 1.25, 2.0})) }

go run ./ok

10
3.75

The compiler type-checks Sum against the constraint, so total += value is legal for every member of the union. That is the reason the body cannot call a method that only one of the types has: Go generics are not a macro and cannot see the concrete type.

The same mistake in Go

A slice of strings is not in the union, and the compiler says so in one line, with the type and the constraint:

package main import "fmt" type Number interface { ~int | ~float64 } func Sum[T Number](values []T) T { var total T for _, value := range values { total += value } return total } func main() { fmt.Println(Sum([]string{"a", "b"})) }

go build -o /tmp/badbin ./bad

# example.com/gen/bad
bad/main.go:18:17: string does not satisfy Number (string missing in ~int | ~float64)

One line, at the call, naming both sides. It is shorter than the C++ message because Go checks the call against an interface rather than substituting a type into a template, and it is also less informative: the compiler stops at the first missing member of the union and says nothing about the body.

What differs and why

Question C++ templates Go type parameters
When is the code checked? Per instantiation, in the body Once, against the constraint
What can a constraint say? Any expression: concepts, requires, specializations Types, methods, unions and comparable
Can the generic call a method of one type? Yes, if that instantiation has it Only a method in the constraint
Non-type parameters, variadic packs? Yes No
What does the binary contain? One copy per instantiation One copy per memory layout, with a dictionary for the methods

Templates are a second language inside C++, and libraries such as the standard containers, ranges and Eigen are built with it. Go generics are a tool for containers and algorithms, and the Go team has said no to the rest on purpose: no specialization, no metaprogramming, no code that runs at compile time. A programmer who needs a template metaprogram stays in C++, and that is a fair reason to.

The Go lessons are type parameters and constraints and generic types, inference and the standard library; the C++ lesson is function templates.

The C++ programs were built with g++ 15.2.0 (Alpine 15.2.0) at -O2 and the Go programs with go 1.26.10, all run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev