GCC Newspaper
OCTOBER 6, 2026
Date
/
Architectures
Components
Topics
News & Policy
Other
c++/templates

C++: Fix folding of CONSTRUCTOR in templates to avoid invalid expressions.

C++ template instantiation now correctly avoids folding CONSTRUCTORs that have already been processed, fixing an issue with template expression substitution.

This commit addresses a bug in C++ template instantiation where the compiler attempted to re-fold a CONSTRUCTOR expression within a template. This occurred after the Non-Type Template Parameter Declaration (NSDMI) had already been folded, leading to invalid expressions that the template substitution machinery could not handle.

The fix, implemented in typeck2.cc, prevents the folding of CONSTRUCTORs in such scenarios, resolving the issue and ensuring correct template instantiation. A new test case is added to verify the fix.

In Details

In GCC's C++ frontend, the store_init_value function in typeck2.cc is modified to prevent re-folding of CONSTRUCTOR expressions within template instantiations, particularly when an NSDMI has already been folded. This prevents the generation of malformed intermediate expressions that would fail during template substitution (tsubst). The change ensures that the handling of initializers in templates remains consistent with previously folded constructs.

For Context
CONSTRUCTOR
In C++, a special member function called automatically when an object of a class is created. It is used to initialize the object's members.
template
A C++ feature that allows for generic programming, enabling functions and classes to operate on values of any type without needing to be rewritten for each type.
NSDMI
Non-Type Template Parameter Declaration with Initializer. This allows template parameters to be initialized with values directly within the template declaration.
fold expression
A C++17 feature that allows applying a binary operator over a pack of parameters in a variadic template expansion.
tsubst
Template substitution, the process by which C++ template code is instantiated with specific types or values to generate actual code.
Filed Under: c++templatescompiler bug