# Using the C++11 auto keyword in ITKv5 code

**URL:** <https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682>\
**Category:** Engineering\
**Created:** [February 18, 2018, 12:37pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682 "2018-02-18T12:37:14Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![Niels\_Dekker](https://discourse.itk.org/letter_avatar_proxy/v4/letter/n/9d8465/32.png) [@Niels\_Dekker](https://discourse.itk.org/u/Niels_Dekker)\
**Post date:** [February 18, 2018, 12:37pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/1 "2018-02-18T12:37:16Z")

</div>

On recent patches to ITKv5 that I proposed, I was asked not to use the C++11 _auto_ keyword. For example, in the following code:

```
const auto centerPoint = (*itCircles)->GetCenterPoint();

```

Which I then replaced by the following (hoping to get the patch accepted more easily):

```
const HoughTransformFilterType::CircleType::PointType centerPoint =
    (*itCircles)->GetCenterPoint();

```

Is there an agreement that the last line of code (without _auto_) is better than the fist one (with _auto_)? Because personally I would still prefer the first one.

In general, for a specific type _T_, the statement _T x = f()_ might have an implicit type conversion. Whereas _auto y = f()_ clearly just copies the return value of _f()_ to _y_.

C++ guru Herb Sutter even recommends “AAA Style (Almost Always Auto)”:

> **[GotW #94 Solution: AAA Style (Almost Always Auto)](https://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/)**
>
> Toward correct-by-default, efficient-by-default, and pitfall-free-by-default variable declarations, using “AAA style”… where “triple-A” is both a mnemonic and an evaluation …

---

<div class="post-metadata">

**Author:** ![bill.lorensen](https://discourse.itk.org/user_avatar/discourse.itk.org/bill.lorensen/32/66_2.png) [@bill.lorensen](https://discourse.itk.org/u/bill.lorensen)\
**Post date:** [February 18, 2018, 2:26pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/2 "2018-02-18T14:26:53Z")

</div>

I like the non-auto way because it tells in the same line the type. With  
auto, I need to look elsewhere for the type.

---

<div class="post-metadata">

**Author:** ![phcerdan](https://discourse.itk.org/user_avatar/discourse.itk.org/phcerdan/32/286_2.png) [@phcerdan](https://discourse.itk.org/u/phcerdan)\
**Post date:** [February 18, 2018, 2:32pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/3 "2018-02-18T14:32:57Z")

</div>

From my point of view, the first version with `auto` is better than the second, in terms of maintainability, reusability, but specially readability of the code. I think there is a common misconception with `auto` and type safety. auto is not like the `any` type from weakly typed languages. It guarantees the type safety even more strongly (without narrowing conversions) as you pointed out.

One of the cases where it should be forbidden or used with extreme caution is when type conversions are explicitly needed, for example, the [Eigen math library](https://eigen.tuxfamily.org/dox/TopicPitfalls.html) which uses lazy evaluation for matrix operations.

In this sense, I don’t know if there are similar cases in ITK where type conversion must be explicit or we would get a surprising `auto` type.

---

<div class="post-metadata">

**Author:** ![matt.mccormick](https://discourse.itk.org/user_avatar/discourse.itk.org/matt.mccormick/32/7_2.png) [@matt.mccormick](https://discourse.itk.org/u/matt.mccormick)\
**Post date:** [February 18, 2018, 3:11pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/4 "2018-02-18T15:11:34Z")

</div>

Please review [this patch](https://github.com/InsightSoftwareConsortium/ITKSoftwareGuide/pull/59), which adds `auto` usage guidelines to the ITK Coding Style Guide.

This is consistent with the readability goals outlined in the style guide:

> This chapter describes the ITK Coding Style. Developers must follow these conventions when submitting contributions to the toolkit.
> 
> The following coding-style guidelines have been adopted by the ITK community. To a large extent  
> these guidelines are a result of the fundamental architectural and implementation decisions made  
> early in the project. For example, the decision was made to implement ITK with a C++ core using  
> principles of generic programming, so the rules are oriented towards this style of implementation.  
> Some guidelines are relatively arbitrary, such as indentation levels and style. However, an attempt  
> was made to find coding styles consistent with accepted practices. The point is to adhere to a common  
> style to assist community members of the future to learn, use, maintain, and extend ITK. A common  
> style greatly improves readability.

and naming conventions:

> Other general rules that must be followed in naming ITK constructs are:  
> • Underscores are not used (with the sole exception of enums and member variables).  
> • Variable names are chosen carefully with the intention to convey the meaning behind the code.  
> • Names are generally spelled out; use of abbreviations is discouraged. While this does result in  
> long names, it self-documents the code (e.g. use Dimension, point, size, or vector, instead  
> of D, pt, sz, or vec, respectively). Abbreviations are allowable when in common use, and  
> should be in uppercase as in RGB, or ID for “identifier”.)

and [where VTK landed regarding `auto`](https://docs.google.com/document/d/1h7wIq25d-qimQO8N9sE43fHXKKlHM2sW2ErohfHiuCg/edit).

It avoids duplicate type specification when the type is already specified on the right hand side of an assignment and enables use in range-based `for` loops, but it maintains readability by requiring explicit types otherwise that provide meaning and context.

---

<div class="post-metadata">

**Author:** ![lassoan](https://discourse.itk.org/user_avatar/discourse.itk.org/lassoan/32/27_2.png) [@lassoan](https://discourse.itk.org/u/lassoan)\
**Post date:** [February 18, 2018, 4:21pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/5 "2018-02-18T16:21:04Z")

</div>

> [@matt.mccormick](#):
>
> requiring explicit types otherwise that provide meaning and context

These guidelines seems good for ITK library code. However, it could be useful to distinguish these from recommendations for application code (that just uses ITK), where probably “almost-always auto” style applies. This simpler style could be used in ITK examples, where it may be more important to show how easy to use ITK.

---

<div class="post-metadata">

**Author:** ![spinicist](https://discourse.itk.org/user_avatar/discourse.itk.org/spinicist/32/183_2.png) [@spinicist](https://discourse.itk.org/u/spinicist)\
**Post date:** [February 18, 2018, 5:43pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/6 "2018-02-18T17:43:29Z")

</div>

I completely agree with @lassoan. ITK client code can be incredibly verbose. If you follow the examples, there are often `#typedef`s all over the place, even for types that are only used once. I have generally swapped to `auto` for these kinds of types, and now find it more readable and less error prone. In my opinion, typedefs are even worse than auto for the “having to look up what that type actually is” problem.

But yes, within ITK it is less clear-cut. Personally I am lazy, and `auto` saves me one heck of a lot of typing, so I tend to favour its use.

---

<div class="post-metadata">

**Author:** ![matt.mccormick](https://discourse.itk.org/user_avatar/discourse.itk.org/matt.mccormick/32/7_2.png) [@matt.mccormick](https://discourse.itk.org/u/matt.mccormick)\
**Post date:** [February 18, 2018, 6:26pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/7 "2018-02-18T18:26:32Z")

</div>

Yes, agreed that a more liberal use of `auto` in application code and examples makes it easier and quicker to write. I will make a note in the Style Guide patch to distinguish application code and examples.

Since ITK lines of code are read thousands of times more than it is written, explicit readable code saves much more time than the time required to write the code. As much as possible, the meaning of code should be evident from local context.

Very poor information on the intended meaning of the output:

```auto
auto localValue = crossCorrelation->GetOutput();

```

Poor information on the intended meaning of the output:

```auto
double localValue = crossCorrelation->GetOutput();

```

Good information on the intended meaning of the output:

```auto
ScalarMetricType localValue = crossCorrelation->GetOutput();

```

---

<div class="post-metadata">

**Author:** ![phcerdan](https://discourse.itk.org/user_avatar/discourse.itk.org/phcerdan/32/286_2.png) [@phcerdan](https://discourse.itk.org/u/phcerdan)\
**Post date:** [February 18, 2018, 7:58pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/8 "2018-02-18T19:58:44Z")

</div>

The variable name `localValue` is not conveying meaning! 😃  
We do have the same problem without auto, I have seen this quite often:

`CrossCorrelationFilterType::OutputType localValue = crossCorrelation->GetOutput();`

What about?  
`auto crossCorrelationScalarResult = crossCorrelation->GetOutput()`

We can provide meaning with the type, and/or the variable name.

But yes, I agree GetOutput() is too generic for `auto` to be clear there. It’s not the same as `GetArray()`, or similar. But I think that confusion happens with or without auto.

---

<div class="post-metadata">

**Author:** ![matt.mccormick](https://discourse.itk.org/user_avatar/discourse.itk.org/matt.mccormick/32/7_2.png) [@matt.mccormick](https://discourse.itk.org/u/matt.mccormick)\
**Post date:** [February 18, 2018, 10:11pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/9 "2018-02-18T22:11:48Z")

</div>

Both the instance variable name and the type name can and should convey meaning, but they are not necessarily the same meaning. Types and instances are different and they should be named as appropriate, e.g.

```auto
ScalarMetricType localValue = [...]

```

```auto
ScalarMetricType globalValue = [...]

```

`Scalar` does not belong in the instance name – this is a description of the type, not the instance.

---

<div class="post-metadata">

**Author:** ![blowekamp](https://discourse.itk.org/user_avatar/discourse.itk.org/blowekamp/32/79_2.png) [@blowekamp](https://discourse.itk.org/u/blowekamp)\
**Post date:** [February 20, 2018, 3:24pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/10 "2018-02-20T15:24:27Z")

</div>

What do we think about auto usage in the following case:

```auto
ImageType::Pointer image = ImageType::New();

```

to

```auto
auto image = ImageType::New();

```

This is a case where the the type is “nearly” duplicated on the left and the right. I think declaring a `typedef` or `using` of the class is useful, but not having to define the pointer too would be very nice.

Perhaps the later could be done in the ITK examples?

---

<div class="post-metadata">

**Author:** ![matt.mccormick](https://discourse.itk.org/user_avatar/discourse.itk.org/matt.mccormick/32/7_2.png) [@matt.mccormick](https://discourse.itk.org/u/matt.mccormick)\
**Post date:** [February 20, 2018, 3:38pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/11 "2018-02-20T15:38:01Z")

</div>

The current coding style guidelines patch suggests that `auto` should be used in this case, but we can make that more explicit.

---

<div class="post-metadata">

**Author:** ![Niels\_Dekker](https://discourse.itk.org/letter_avatar_proxy/v4/letter/n/9d8465/32.png) [@Niels\_Dekker](https://discourse.itk.org/u/Niels_Dekker)\
**Post date:** [February 20, 2018, 4:47pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/12 "2018-02-20T16:47:19Z")

</div>

Thank you guys, thanks Matt, for allowing more _auto_ than before 😃

Hope you also allow _auto_ to define a _trailing return type_, in those cases where specifying the return type _before_ the function name (the old style) appears more cumbersome than _after_ the function name (trailing return type). As I did here:

```
template< typename TInputPixelType, typename TOutputPixelType, typename TRadiusPixelType >
auto
HoughTransform2DCirclesImageFilter< TInputPixelType, TOutputPixelType, TRadiusPixelType >
::Circle::GetCenter() const
-> CenterType // Trailing return type!
{
  return m_Center;
}

```

At my proposed patch [ENH: Added HoughTransform2D Circle class, simplified GetCircles() return type](http://review.source.kitware.com/#/c/23139) line 54 of  
[http://review.source.kitware.com/#/c/23139/9/Modules/Filtering/ImageFeature/include/itkHoughTransform2DCirclesImageFilter.hxx](http://review.source.kitware.com/#/c/23139/9/Modules/Filtering/ImageFeature/include/itkHoughTransform2DCirclesImageFilter.hxx)

(Without using _auto_ and _trailing return type_, the return type would have to be specified as  
`typename HoughTransform2DCirclesImageFilter< TInputPixelType, TOutputPixelType, TRadiusPixelType >::Circle::CenterType`, that’s what looks cumbersome to me!)

---

<div class="post-metadata">

**Author:** ![matt.mccormick](https://discourse.itk.org/user_avatar/discourse.itk.org/matt.mccormick/32/7_2.png) [@matt.mccormick](https://discourse.itk.org/u/matt.mccormick)\
**Post date:** [February 20, 2018, 6:57pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/13 "2018-02-20T18:57:25Z")

</div>

Good point, Neils. Trailing return type has been added to the list.

---

<div class="post-metadata">

**Author:** ![Niels\_Dekker](https://discourse.itk.org/letter_avatar_proxy/v4/letter/n/9d8465/32.png) [@Niels\_Dekker](https://discourse.itk.org/u/Niels_Dekker)\
**Post date:** [February 20, 2018, 11:08pm UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/14 "2018-02-20T23:08:14Z")

</div>

Thanks, Matt. Another valid _auto_ use case, in my opinion, is to store a _lambda expression_ in a variable, in order to use it multiple times:

```
double SumOfSquares(const double a, const double b)
{
    // Storing the lambda in a closure variable, 'square', in order to use it twice:
    auto square = [](const double x) { return x * x; };

    return square(a) + square(b);
}

```

In this case, an _std::function_ variable could be used instead, but that would cause a performance penalty.

---

<div class="post-metadata">

**Author:** ![matt.mccormick](https://discourse.itk.org/user_avatar/discourse.itk.org/matt.mccormick/32/7_2.png) [@matt.mccormick](https://discourse.itk.org/u/matt.mccormick)\
**Post date:** [February 21, 2018, 1:26am UTC](https://discourse.itk.org/t/using-the-c-11-auto-keyword-in-itkv5-code/682/15 "2018-02-21T01:26:32Z")

</div>

Yes, … added to the patch!

Note that @dzenanz is adding support to the new multi-threading framework for ITK 5.0 to elegantly accept lamda’s and _std::function_ – exciting!
