Skip to content

WIP: DO NOT MERGE — Modernize image iterators to eliminate const_cast via VIsConst templating - #6142

Closed
hjmjohnson wants to merge 6 commits into
InsightSoftwareConsortium:mainfrom
hjmjohnson:modernize-iterators-remove-const-cast
Closed

hjmjohnson wants to merge 6 commits into
InsightSoftwareConsortium:mainfrom
hjmjohnson:modernize-iterators-remove-const-cast

Conversation

@hjmjohnson

Copy link
Copy Markdown
Member

This PR is a working draft and is likely a throwaway. It is published for visibility and discussion only. Closes #6141 if the design is accepted; otherwise it will be closed and re-opened as a series of smaller PRs.

Before any subset of this work is finalized it must be broken into smaller, individually reviewable units and validated against downstream consumers — at minimum ANTs, BRAINSTools, and 3D Slicer — to surface API-compatibility regressions that ITK's own test suite cannot detect (template alias deduction quirks, CTAD edge cases, slicing-through-inheritance call sites, etc.).

What this branch contains

13 ENH commits collapsing the legacy XxxConstIterator<T> / XxxIterator<T> class pairs into single XxxIteratorBase<T, bool VIsConst> class templates with the legacy names preserved as alias templates.

Unit Cluster
1 ImageConstIterator / ImageIterator (root)
2 (×7 pairs) ImageIteratorWithIndex family: Region / Linear / Slice / Random / RandomNonRepeating / RegionExclusion
3 ImageScanlineIterator
4 ImageReverseIterator / ImageRegionReverseIterator
5 LineIterator
6 ConditionalIterator + FloodFilled* cluster
7 ImageRegionIterator (non-WithIndex)

Plus an earlier design spike commit ENH: Add NeighborhoodIteratorBase<T,BC,VIsConst> spike which is not yet wired into legacy neighborhood class names.

ITK in-tree status: build green at 1360/1360 targets, 3270/3270 ctests passing.

Why this is likely a throwaway
  • Downstream validation is not yet done. The ITK test suite passes, but downstream codebases use ITK iterator types in ways that this PR has not exercised:
    • ANTs, BRAINSTools, and Slicer all template helper functions on iterator types and may rely on inheritance relationships that the alias-template form silently changes.
    • Implicit conversions between non-const and const iterators were previously by inheritance + slicing; they are now via an explicit converting constructor. Some consumer code paths break (one was already caught and fixed in Modules/Registration/Common/test/itkKappaStatisticImageToImageMetricTest.cxx — there will be more in the wild).
    • using ImageRegionIterator<const T> patterns no longer route to the const specialization the way the inheritance form did; consumers must switch to ImageRegionConstIterator<T>.
  • The neighborhood cluster is not addressed. Four const_cast sites remain in ConstNeighborhoodIterator, ConstShapedNeighborhoodIterator, ShapedNeighborhoodIterator. The spike commit prototypes the right design (composition instead of ConstShapedNeighborhoodIterator : private NeighborhoodIterator) but wiring it into the legacy class names is itself a ~1700-line replacement that warrants a separate PR.
  • Per-unit landing is preferable. Each of the 13 ENH commits is self-contained and could land on main as its own PR, allowing CDash to surface regressions one cluster at a time. A single 67-file PR is hard to bisect if a downstream regression emerges months later.
Recommended path forward
  1. Validate this branch against ANTs / BRAINSTools / Slicer trees in their respective CI configurations. Capture every regression as a separate issue.
  2. Decide whether the templated-base + alias-template approach is the desired endpoint, or whether a different strategy (e.g., inheritance preserved with mutable storage; or a deprecation cycle that asks consumers to migrate explicitly) is preferred.
  3. If the design is accepted, close this PR and re-open as ~7 smaller PRs (one per Unit), each with its own downstream-CI run.
  4. Open a follow-up issue/PR for the neighborhood cluster, building on the existing spike commit.

@github-actions github-actions Bot added type:Infrastructure Infrastructure/ecosystem related changes, such as CMake or buildbots type:Testing Ensure that the purpose of a class is met/the results on a wide set of test cases are correct area:Core Issues affecting the Core module area:Registration Issues affecting the Registration module labels Apr 25, 2026
…ests

Introduces itk::NeighborhoodIteratorBase<TImage, TBoundaryCondition, bool VIsConst>
and itk::ShapedNeighborhoodIteratorBase<TImage, TBoundaryCondition, bool VIsConst>
as a design spike for a const-correct neighborhood-iterator family that does not
rely on const_cast. The new header is not yet wired into the legacy iterator
class names; legacy ConstNeighborhoodIterator, NeighborhoodIterator,
ConstShapedNeighborhoodIterator, and ShapedNeighborhoodIterator are unchanged.

Design:
* std::conditional_t selects ImagePointer, InternalPixelPointer, and neighborhood
  storage at compile time based on VIsConst; no const_cast in the base.
* Write methods (SetPixel, SetCenterPixel, SetNeighborhood, inner Set) are
  SFINAE-disabled on VIsConst=true, yielding a readable diagnostic at the call
  site when a caller tries to mutate through a const iterator.
* Composition, not private inheritance, in the shaped pair: ShapedNeighborhoodIteratorBase
  composes NeighborhoodIteratorBase<..., VIsConst> through an m_Base member,
  eliminating the const_cast at legacy itkConstShapedNeighborhoodIterator.h:216
  and :256.
* Unified InnerIteratorT<VInnerIsConst> replaces the parallel ConstIterator /
  Iterator pair; mutating Begin()/End() are SFINAE-gated on outer VIsConst.
* Non-const -> const converting ctor is enabled; the reverse is a compile
  error by construction.

Testing: itkNeighborhoodIteratorBaseSpikeTest exercises the static_assert
structural claims. itkNeighborhoodIteratorBaseRuntimeTest instantiates both
const and non-const specializations on an itk::Image<float,3>, verifies
Set round-trips through the image buffer, exercises the shaped pair with
an active-offset stencil, and proves the converting-ctor and compile-fail
asymmetries via std::is_constructible_v.
@hjmjohnson
hjmjohnson force-pushed the modernize-iterators-remove-const-cast branch 2 times, most recently from a10180f to f03a27c Compare April 25, 2026 22:41
@hjmjohnson

Copy link
Copy Markdown
Member Author

@N-Dekker THIS IS NOT READY, but I thought you might be interested in this DRAFT re-engineering to remove const_cast from many of the iterators.

This is intended to be a throwaway PR, but I thought you might like to comment on the general approach and draw inspiration.

Do not feel obligated to put much time into this. It was a distraction that I now need to shelve.

@hjmjohnson
hjmjohnson force-pushed the modernize-iterators-remove-const-cast branch from f03a27c to 824b09c Compare April 26, 2026 12:09
@hjmjohnson

Copy link
Copy Markdown
Member Author

Triage finding: C++17 incompatibility blocks this approach.

CI surfaced a fundamental issue: GCC and MSVC reject CTAD synthesis through alias templates under C++17 (it is a C++20 feature, P1814). Apple Clang accepts it as a C++17 extension, which is why ITK.macOS and ITK.macOS.Python pass while ITK.Linux, ITK.Linux.Python, ITK.Windows, and ARMBUILD-Ubuntu-24.04-arm all fail with 50 / 3 / 50 compile errors respectively.

Sample diagnostic + breaking call site
itkVnlHalfHermitianToRealInverseFFTImageFilter.hxx:72:37: error: alias template
  deduction only available with '-std=c++20' or '-std=gnu++20'

Source line (pre-existing, unmodified by this PR):

for (ImageRegionIteratorWithIndex oIt(outputPtr,
       outputPtr->GetLargestPossibleRegion()); !oIt.IsAtEnd(); ++oIt)

This worked when ImageRegionIteratorWithIndex was a real class template; the alias-template form requires C++20 alias-template CTAD synthesis to deduce TImage.

Implications for the redesign
  • The "preserve legacy names as alias templates" strategy as currently formulated is not C++17-compatible.
  • Three plausible paths:
    1. Bump ITK's minimum C++ standard to C++20 (project-wide decision; out of scope for this PR).
    2. Keep the legacy names as real class templates that derive trivially from the new XxxIteratorBase<T, VIsConst>, restoring class-template CTAD. Costs two extra one-line classes per pair but recovers C++17 compatibility.
    3. Migrate every CTAD call site in ITK and its downstream consumers to spell TImage explicitly. High churn; affects ANTs / BRAINSTools / Slicer.

Path 2 looks like the only viable one for staying on C++17. It does not change the const-correctness story (the base still has bool VIsConst and SFINAE-gated writes), and it eliminates one of the trickier corners of this PR (alias-template CTAD adapter guides).

This is exactly the kind of downstream-style finding that motivated the WIP: DO NOT MERGE framing. The PR remains a draft; further triage paused until the alias-template-vs-class-template question is resolved.

@hjmjohnson
hjmjohnson force-pushed the modernize-iterators-remove-const-cast branch from 824b09c to 5476eb9 Compare April 26, 2026 12:28
@dzenanz

dzenanz commented Apr 26, 2026

Copy link
Copy Markdown
Member

I think we bumped required C++ version from 14 to 17 during v6.0 change window. Let's wait at least until ITK 6.1 to bump it again. The option 2 does not seem very costly.

@hjmjohnson

Copy link
Copy Markdown
Member Author

Update — converted alias templates to thin class-template wrappers (option 2 from the prior comment).

Pushed 5476eb93c3. The 34 legacy iterator names are now real class templates that derive from their XxxIteratorBase<TImage, VIsConst> (with using Superclass::Superclass to inherit constructors), plus explicit deduction guides per wrapper. Local macOS build green at 1435/1435 targets; awaiting CI on Linux / Windows / ARM to confirm the C++17 alias-template-CTAD diagnostic is gone.

Why this should fix the C++17 incompatibility

C++17 forbids CTAD synthesis through alias templates (P1814 only landed in C++20). Real class templates synthesize their own deduction guides from their constructors, which works under C++17. Pre-existing call sites such as

for (ImageRegionIteratorWithIndex oIt(outputPtr, outputPtr->GetLargestPossibleRegion()); ...)

now resolve through the wrapper class template's own CTAD instead of going through an alias template, so GCC and MSVC should accept it.

The using Superclass::Superclass form does not participate in CTAD on C++17 (inherited-ctors-as-CTAD-sources is also C++20). To compensate, each wrapper carries explicit deduction guides for the (SmartPointer<T>, RegionType) and raw-pointer forms.

@hjmjohnson
hjmjohnson force-pushed the modernize-iterators-remove-const-cast branch from 5476eb9 to 9510ca3 Compare April 26, 2026 12:48
Adds a non-pure virtual operator() overload on itk::ImageBoundaryCondition that
accepts const Neighborhood<const InternalPixelType*, Dim>*, in parallel to the
existing overload taking const Neighborhood<InternalPixelType*, Dim>*. The new
overload's default body forwards to the legacy signature via reinterpret_cast;
the two Neighborhood<> instantiations are layout-compatible. Same treatment for
the two-output-image overload.

Also adds matching BoundaryCondition(const ConstNeighborhoodType*, ...) overloads
on itk::Functor::NeighborhoodAccessorFunctor and
itk::VectorImageNeighborhoodAccessorFunctor.

Zero source-break for existing ImageBoundaryCondition subclasses (in-tree or
downstream): they continue to override only the legacy overload, and any call
to the new const-path overload falls through the default to their existing
implementation. Subclasses that want a perf-optimized const-path override may
add one, but it is not required.

Motivation: a templated-const neighborhood-iterator base (see the companion
NeighborhoodIteratorBase spike in this series) inherits from
Neighborhood<const InternalPixelType*, Dim> on its VIsConst=true instantiation.
The existing boundary-condition dispatch chain cannot accept it without this
overload. Option B was selected over (A) breaking the ImageBoundaryCondition
template surface and (C) re-architecting Neighborhood<> for pointer-constness
polymorphism, because it requires zero source edits in any existing
ImageBoundaryCondition subclass (including out-of-tree remote modules).

Validated: full ITK build clean with BUILD_EXAMPLES=ON and six remote modules
enabled (6937/6937 targets). Full ctest suite clean (3637/3637 passed, zero
regressions vs. main baseline).
@hjmjohnson
hjmjohnson force-pushed the modernize-iterators-remove-const-cast branch from 9510ca3 to 028aad2 Compare April 26, 2026 13:50
@hjmjohnson

Copy link
Copy Markdown
Member Author

Update — addressed -Woverloaded-virtual cascade.

The wrapper-class conversion compiled cleanly on GCC C++17 (CTAD diagnostic is gone), but Linux dashboard treated the -Woverloaded-virtual warnings as fatal. The base ImageBoundaryCondition gained two new operator() overloads (taking const ConstNeighborhoodType *) in commit 3ecc3bc35d; legacy derivatives (ConstantBoundaryCondition, ZeroFluxNeumannBoundaryCondition, PeriodicBoundaryCondition) only override the original two overloads, so GCC reported the new overloads as "hidden" at every template instantiation.

Fix: added using Superclass::operator(); to each derived class to bring the base overloads into scope. Folded into 48a6b4d680 (formerly 3ecc3bc35d).

New HEAD: 028aad2bf5. CI re-running.

Collapse the legacy XxxConstIterator<T> / XxxIterator<T> class pairs
into single XxxIteratorBase<T, bool VIsConst> class templates for the
non-WithIndex image-iterator family. Pointer-like members switch
element-const via std::conditional_t; write methods are SFINAE-gated
on !VIsConst. The legacy class names are preserved as alias templates
so existing consumers compile unchanged.

Covers:
* ImageIterator / ImageConstIterator (root)
* ImageScanlineIterator / ImageScanlineConstIterator
* ImageReverseIterator / ImageReverseConstIterator
* ImageRegionReverseIterator / ImageRegionReverseConstIterator
* ImageRegionIterator / ImageRegionConstIterator

Also fixes a previously hidden Set() call that dispatched through
two-arg AccessorType::Set instead of three-arg
AccessorFunctorType::Set, which broke VectorImage compatibility on
the non-const path.
Collapse the seven legacy XxxConstIteratorWithIndex<T> /
XxxIteratorWithIndex<T> class pairs into single
XxxIteratorWithIndexBase<T, bool VIsConst> class templates. Pointer-like
members switch element-const via std::conditional_t; write methods are
SFINAE-gated on !VIsConst. Legacy names are preserved as alias templates.

Covers:
* ImageIteratorWithIndex (root)
* ImageRegionIteratorWithIndex
* ImageLinearIteratorWithIndex
* ImageSliceIteratorWithIndex
* ImageRandomIteratorWithIndex
* ImageRandomNonRepeatingIteratorWithIndex
* ImageRegionExclusionIteratorWithIndex

Also updates itkKappaStatisticImageToImageMetricTest.cxx, which
previously used the legacy ImageRegionIteratorWithIndex<const T>
pattern that no longer routes to the const specialization through
the alias-template form.
Collapse LineConstIterator<T> / LineIterator<T> into a single
LineIteratorBase<T, bool VIsConst> class template, eliminating the
const_cast in the previous LineIterator leaf. Legacy class names
remain as alias templates so existing consumers compile unchanged.
Collapse the legacy ConditionalIterator and FloodFilled* class pairs
into single Base<..., bool VIsConst> class templates with the legacy
class names preserved as alias templates.

Covers:
* ConditionalIterator / ConditionalConstIterator
* FloodFilledFunctionConditionalIterator / ...Const variants
* FloodFilledImageFunctionConditionalIterator / ...Const variants
* FloodFilledSpatialFunctionConditionalIterator / ...Const variants
* ShapedFloodFilledFunctionConditionalIterator / ...Const variants
* ShapedFloodFilledImageFunctionConditionalIterator / ...Const variants
@hjmjohnson
hjmjohnson force-pushed the modernize-iterators-remove-const-cast branch from 028aad2 to 3d21ea1 Compare April 26, 2026 14:43
@hjmjohnson

Copy link
Copy Markdown
Member Author

Update — full CI green except ITK.Linux.Python (still building) and the intentional WIP gate.

The wrapper-class redesign + using Superclass::operator() cascade is fully validated across the matrix. The original C++17 alias-template-CTAD diagnostic is gone on every GCC and MSVC build:

Pipeline Status
ITK.Linux ✅ pass
ITK.Windows ✅ pass
ITK.macOS ✅ pass
ITK.macOS.Python ✅ pass
ARMBUILD-Ubuntu-24.04-arm ✅ pass
ARMBUILD-x86_64-rosetta ✅ pass
ARMBUILD-Python ✅ pass
ITK.Linux.Python ⏳ in progress

The WIP marketplace gate stays pending intentionally as long as the title carries the WIP: prefix.

The design pivot from alias-templates to thin class-template wrappers held up — pre-existing CTAD call sites like for (ImageRegionIteratorWithIndex oIt(outputPtr, ...); ...) now route through real class-template CTAD synthesis on C++17 instead of needing C++20's P1814.

This PR is now in a state where downstream validation against ANTs / BRAINSTools / Slicer would be productive. Per the original framing it remains a draft pending that step plus the per-unit split.

@hjmjohnson

Copy link
Copy Markdown
Member Author

This PR has run it's course of usefulness. It demonstrates feasibility, but will need to wait until other priorities are addressed, and will likely need to be a series of much smaller incremental commits with Slicer/BRAINSTools/ANTs etc build testing integrated.

Will re-open or break apart when time permits in the future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:Core Issues affecting the Core module area:Registration Issues affecting the Registration module type:Infrastructure Infrastructure/ecosystem related changes, such as CMake or buildbots type:Testing Ensure that the purpose of a class is met/the results on a wide set of test cases are correct

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ENH: Modernize image iterators to eliminate const_cast via VIsConst templating

2 participants