Skip to content

ENH: Eliminate const_cast from itk::ImageIterator - #7021

Closed
mymonin wants to merge 1 commit into
InsightSoftwareConsortium:mainfrom
mymonin:refactor-image-iterator
Closed

mymonin wants to merge 1 commit into
InsightSoftwareConsortium:mainfrom
mymonin:refactor-image-iterator

Conversation

@mymonin

@mymonin mymonin commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

Addresses #6141 for the itk::ImageIterator and itk::ImageConstIterator template classes.

Compared to the changes described in #6142 (comment) which were left unmerged:

  • It is a singular patch focused on a single class pair
  • Access semantics are defined directly by the image template type constness, no additional boolean parameter needed
  • Downstream consumers can keep including the same headers and using ImageIterator<const T>

I am submitting this PR not only to propose a design variant, but also to highlight that fixing #6141 would incidentally fix all of #7003, and also avoid the "hack" (as described by the participants) needed for #6955 regarding the TImage::GetBufferPointer() overload.

The downside is that these changes should break code that specifically relies on itk::ImageIterator inheriting from itk::ImageConstIterator, e.g. using ImageIterator<TImage>::Superclass. The fact that none of the tests nor derived iterators like itk::ImageRegionIterator required subsequent changes suggests this should not occur very often, if at all. However, I am not familiar with the cited dependent codebases (ANTs, BRAINSTools and Slicer) so I could be wrong.

Note: the diff looks large but most of it is moving the content of itkImageConstIterator.h to itkImageIterator.h.

PR Checklist

  • No API changes were made (or the changes have been approved)
  • No major design changes were made (or the changes have been approved)
  • Added test (or behavior not changed)
  • Updated API documentation (or API not changed)
  • Added license to new files (if any)
  • Added Python wrapping to new files (if any) as described in ITK Software Guide Section 9.5
  • Added ITK examples for all new major features (if any)

Refer to the ITK Software Guide for
further development details if necessary.

@github-actions github-actions Bot added type:Enhancement Improvement of existing methods or implementation 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 labels Oct 27, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for contributing a pull request! 🙏

Welcome to the ITK community! 🤗👋☀️

We are glad you are here and appreciate your contribution. Please keep in mind our community participation guidelines. 📜
More support and guidance on the contribution process can be found in our contributing guide. 📖

This is an automatic message. Allow for time for the ITK community to be able to read the pull request and comment
on it.

@greptile-apps

greptile-apps Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[High impact] The change reaches ITK's shared image-iteration API.

Fix mixed writable/read-only comparisons before merging.

Findings

  1. P1 Mixed iterator comparisons fail ▶
  2. P2 Read-only class identity changes ▶
  3. P2 Pixel access comments mislead ▶

Summary

Makes image constness control ImageIterator access and retains ImageConstIterator as a compatibility class.

  • Image iterators now take their access rules from the image type.

mymonin explicitly acknowledged that losing inheritance from ImageConstIterator and removing ImageIterator::Superclass may break downstream code. That structural change is not reported separately.

Reviews (1) · Last reviewed commit: "ENH: Refactor ImageIterator/ImageConstIt..." · Reviewed by Greptile

The original inheritance-based design of the iterator class pairs has several
problems, notably the pervasive need to const_cast away the pointer-to-const
member whenever an iterator needs write access. This opens up opportunities
for accidental or deliberate const-correctness violation.

This refactor makes itk::ImageIterator a standalone template class that
models both read-only and read/write access semantics based solely on the
constness of the template type.

ImageConstIterator<T> then functionally acts as an alias template for
ImageIterator<const T>. It is implemented as a minimal derived class due to
CTAD not being available for alias templates pre-C++20.
@mymonin
mymonin force-pushed the refactor-image-iterator branch from 4e86f55 to 10c4420 Compare October 29, 2026 07:44

@dzenanz dzenanz left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me. It would be good if someone else reviewed this before merging.

@dzenanz
dzenanz requested a review from SimonRit October 30, 2026 20:23
@dzenanz

dzenanz commented Oct 30, 2026

Copy link
Copy Markdown
Member

The const_casts are only removed from the base class. ImageRegionIterator still derives from ImageRegionConstIterator → ImageConstIterator, and still uses const_cast at itkImageRegionIterator.h:118. ImageIteratorWithIndex does too. Did you envision these as follow-ups? We should probably change all of them together.

@SimonRit SimonRit left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, looks good to me. Two points for your consideration:

  • should you (first) revert 9a6c182 in this PR?
  • I would remove all includes of itkImageConstIterator.h in other files and trigger a compilation error if it is included with ITK_FUTURE_LEGACY_REMOVE guards.

@mymonin

mymonin commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor Author

The const_casts are only removed from the base class. ImageRegionIterator still derives from ImageRegionConstIterator → ImageConstIterator, and still uses const_cast at itkImageRegionIterator.h:118. ImageIteratorWithIndex does too. Did you envision these as follow-ups? We should probably change all of them together.

Yes, I think eventually all other iterators should follow the same rework. I kept this PR focused to Image[Const]Iterator only because it is easier to review and fix if any problem is identified at this stage. Also, quoting #6042: "Per-unit landing is preferable. Each of the 13 ENH commits is self-contained and could land on main as its own PR".

edit: For the record, I applied the same refactor to itkImageRegionIterator in a local branch out of curiosity. It did work almost as well, except for a constructor ambiguity issue coming from itkImageRegionReverseIterator. So then I would have to either make a temporary fix to the reverse iterator or refactor it entirely as well... At this point, I thought this might as well become a separate PR.

@mymonin

mymonin commented Oct 31, 2026

Copy link
Copy Markdown
Contributor Author

should you (first) revert 9a6c182 in this PR?

Since only one iterator pair is modified so far, we should keep using the changes of 9a6c182 for all the other iterators.

I would remove all includes of itkImageConstIterator.h in other files and trigger a compilation error if it is included with ITK_FUTURE_LEGACY_REMOVE guards.

Good point, I am actually not so familiar with the migration strategy in ITK. I tried to make the PR minimal and as backward compatible as possible e.g. by keeping the now mostly empty itkImageConstIterator.h header. But I understand it might be better to fail loudly instead? Especially considering that the required change for users is straightforward ("include itkImageIterator.h instead").

@SimonRit

Copy link
Copy Markdown

Good point, I am actually not so familiar with the migration strategy in ITK. I tried to make the PR minimal and as backward compatible as possible e.g. by keeping the now mostly empty itkImageConstIterator.h header. But I understand it might be better to fail loudly instead? Especially considering that the required change for users is straightforward ("include itkImageIterator.h instead").

The transition is made with this ITK_FUTURE_LEGACY_REMOVE define which is OFF by default. An alternative is to use ITK_FUTURE_DEPRECATED, see e.g.
https://github.com/InsightSoftwareConsortium/ITK/blob/main/Modules/Core/Common/include/itkSingleton.h#L150-L158
I'll let @dzenanz decide what's preferable.

@dzenanz

dzenanz commented Oct 31, 2026

Copy link
Copy Markdown
Member

#include "itkImageConstIterator.h" appears in a whole bunch of places. If we deprecate it, we will have to do a lot of updates everywhere. Perhaps we can do the deprecation (probably via future legacy) once all the iterators have been const-refactored.

@hjmjohnson hjmjohnson left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes for one reason: the fix for #7003 is not in place yet, and nothing tests for it. A downstream build forest found no regressions from this PR.

ImageIterator<const T>::Set and Value() = x now correctly fail to compile. But the case #7003 reports still compiles on this branch, because ImageRegionIterator<const T> derives from ImageRegionConstIterator → ImageConstIterator, which keeps the const_cast:

auto it = itk::ImageRegionIterator<const ImageType>{ constImage, constImage->GetBufferedRegion() };
it.Set(2); // still compiles

Please either narrow the PR description ("would incidentally fix all of #7003" holds only once the derived iterators are refactored too) or extend the change. In both cases, add a compile-time negative test (inline suggestion on the GTest) so the fix is checked rather than assumed. The other inline comments are improvements and judgement calls, not blockers.

Design context: this is a narrower take on #6141 than the closed #6142. #6142 stalled partly because it had no downstream validation, so I ran that validation here.

Downstream build forest: no regressions

ITK built with every default module, Python wrapping, and Module_RLEImage ON (RLEImage specializes both iterator classes, and PR CI does not build it because it is EXCLUDE_FROM_DEFAULT). The PR was merged locally onto a recent main; consumers were built against it with USE_SYSTEM_ITK on macOS arm64.

Consumer Result
ITK, including RLEImage builds
ANTs builds, ctest 179/179 (same as without this PR)
BRAINSTools builds, ctest 458/458 (same as without this PR)
SimpleITK, Cleaver, PerformanceBenchmarking, Impact, TractographyTRX, RTK build

elastix, c3d, SimpleITKFilters, TubeTK, and some remote modules failed for reasons unrelated to this PR: removed VNL/legacy macros, a configure-time target clash, and missing headers. The one iterator-looking failure, a TubeTK test using ImageRegionIteratorWithIndex without including it, fails identically against main's headers.

API changes measured with compile probes

These compile on main and fail on this branch (clang, -std=c++17 -fsyntax-only):

  1. ImageIterator<T>::Superclass
  2. template <class T> void f(const ImageConstIterator<T> &); f(imageIterator); (deduction no longer sees a base)
  3. void f(ImageConstIterator<T> &); f(imageIterator); (non-const reference)
  4. ImageConstIterator<T> * p = &imageIterator;

Silent change: f(const ImageConstIterator<T> &) given an ImageIterator now binds to a converted temporary, not the original object.

No forest consumer uses any of these shapes, so the measured cost is zero. They are still API breaks without an ITK_LEGACY_REMOVE path, and they belong in the migration guide.

Still compile on this branch: CTAD for both classes with SmartPointer, ConstPointer, and raw pointers; mutable-to-const conversion; mixed comparisons in both operand orders; overloads on the two types.

Commit message
  • "ImageConstIterator then functionally acts as an alias template for ImageIterator": ImageIterator<const T> does not convert to ImageConstIterator<T> (inherited constructors exclude copy/move constructors), so the two are not interchangeable. Please qualify the sentence.
  • Four body lines run 75–77 characters; ITK's limit is 72.
How this review was produced

AI-assisted (Claude Code): two-axis review (standards, and spec against #6141/#7003), compile probes, and the forest run. I reviewed the findings and the probes.

@hjmjohnson

Copy link
Copy Markdown
Member

Thank you, @mymonin, for this PR. Making the image's constness choose between read-only and read/write access is the design #6141 needed; the earlier attempt in #6142 had missed it.

#7065 continues this work. Its first commit is your commit, unchanged and with you as author. The rest of the PR applies the same pattern to every image iterator family, so Set() no longer compiles on an iterator over a const image (#7003). It also adds compile-time tests and a downstream forest build. Review and comments there are welcome. Once #7065 merges, this PR can be closed as superseded.

@hjmjohnson

Copy link
Copy Markdown
Member

Closing as superseded by #7065, which contains this PR's commit unchanged (authored by @mymonin) and applies the same design to every image iterator family. Thank you, @mymonin.

How the open review threads here are handled in #7065:

  • const-qualified images can be modified via itk::ImageRegionIterator<const ImageType> #7003 gate only on ImageIterator: every writable iterator now omits Set() for a const image.
  • Negative compile-time test: NoWriteAccessToConstImage checks Set() for 13 writable iterator templates, and Value() assignability for 10.
  • ImageIterator<const T> to ImageConstIterator<T>: converts in both directions; ConstNonConstConversionAndComparison checks it for all 13 iterator pairs.
  • API break and migration guide: documented in the ITK 6 migration guide. itkImageIterator.hxx remains as a one-line include, and \ingroup ImageIterators and ITK_TEMPLATE_EXPORT are back.
  • Unconstrained TOtherImage in comparisons: ENH: Select image iterator access by image constness (supersedes #7021) #7065 compares only iterators over the same image type, with or without const, matching the conversion rule. A cross-image comparison like the 2D slice case can be added later if it is needed.
  • Duplicated copy constructor: now = default.
  • Stale comments and \sa links: fixed.

@hjmjohnson hjmjohnson closed this Nov 5, 2026
hjmjohnson added a commit that referenced this pull request Nov 18, 2026
ENH: Select image iterator access by image constness (supersedes #7021)
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 type:Enhancement Improvement of existing methods or implementation 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.

4 participants