Repository navigation
WIP: DO NOT MERGE — Modernize image iterators to eliminate const_cast via VIsConst templating - #6142
hjmjohnson wants to merge 6 commits into
Conversation
…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.
a10180f to
f03a27c
Compare
|
@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. |
f03a27c to
824b09c
Compare
|
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 Sample diagnostic + breaking call siteSource line (pre-existing, unmodified by this PR): for (ImageRegionIteratorWithIndex oIt(outputPtr,
outputPtr->GetLargestPossibleRegion()); !oIt.IsAtEnd(); ++oIt)This worked when Implications for the redesign
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 This is exactly the kind of downstream-style finding that motivated the |
824b09c to
5476eb9
Compare
|
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. |
|
Update — converted alias templates to thin class-template wrappers (option 2 from the prior comment). Pushed Why this should fix the C++17 incompatibilityC++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 |
5476eb9 to
9510ca3
Compare
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).
9510ca3 to
028aad2
Compare
|
Update — addressed The wrapper-class conversion compiled cleanly on GCC C++17 (CTAD diagnostic is gone), but Linux dashboard treated the Fix: added New HEAD: |
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
028aad2 to
3d21ea1
Compare
|
Update — full CI green except ITK.Linux.Python (still building) and the intentional WIP gate. The wrapper-class redesign +
The The design pivot from alias-templates to thin class-template wrappers held up — pre-existing CTAD call sites like 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. |
|
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. |
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 singleXxxIteratorBase<T, bool VIsConst>class templates with the legacy names preserved as alias templates.ImageConstIterator/ImageIterator(root)ImageIteratorWithIndexfamily: Region / Linear / Slice / Random / RandomNonRepeating / RegionExclusionImageScanlineIteratorImageReverseIterator/ImageRegionReverseIteratorLineIteratorConditionalIterator+FloodFilled*clusterImageRegionIterator(non-WithIndex)Plus an earlier design spike commit
ENH: Add NeighborhoodIteratorBase<T,BC,VIsConst> spikewhich 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
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 toImageRegionConstIterator<T>.const_castsites remain inConstNeighborhoodIterator,ConstShapedNeighborhoodIterator,ShapedNeighborhoodIterator. The spike commit prototypes the right design (composition instead ofConstShapedNeighborhoodIterator : private NeighborhoodIterator) but wiring it into the legacy class names is itself a ~1700-line replacement that warrants a separate PR.mainas 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
mutablestorage; or a deprecation cycle that asks consumers to migrate explicitly) is preferred.