a function returning Eigen::VectorXd failed type inference

Dear all,

I often use Eigen, and when I make a function which returns Eigen::VectorXd and then call it to set a variable type as type inference, "auto", I failed to get correct returned value.

Does "auto" have risk to miss type inference?

A psuedo code is below

1
2
3
4
5
6
7
8
9
10
11
12
13
// CAUTION: I did not test this code as to my question.
// This is a just psuedo code

Eigen::VectorXd func(){
   return Eigen::VectorXd::Zero(1000);
};

int main(){
  // fail
  auto ret1 = func();
  // succeed
  Eigen::VectorXd ret2 = func();
}
Last edited on
Does "auto" have risk to miss type inference?
auto was introduced to allow us mortals to name lambda's and all the really complicated and largely irrelevant types introduced in C++11.

It also turns out that iterator types could be "forgotten" as they too are largely irrelevant intermediate types introduced by the standard library. That's a good things. For example, you can now change your container without having to rewrite all access to it.

Then respectable folk like Herb Sutter started suggesting that auto be used everywhere. That's a bad thing. I mean, what is the benefit of auto i = 0;? That's something I see all the time.
https://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/

Now, template deduction is necessary to make templates more consumable. And "auto" is type deduction to make library features more consumable. The problem is when the two are put together, you have to be very careful. If you're lucky, you'll get a compiler error that you'll immediately understand. If not, welcome to C++ :)

Does "auto" have risk to miss type inference?
Yes.
Last edited on
Dear kbw

Thank you for your kind reply.

I understand type deduction "auto" has risk to miss type inference.

It is so convenient to use "auto", but as you suggested, there is some risk.
I am going to restrict its use in the case that types are determined as possible as identity.

But, in C++, type deduction is particularly useful to infer template class which entails cumbersome and long type name. And, probably the cases that you told me, STL containers, and I asked you "Eigen::VectorXd", corresponds to such a case.

Is there a guideline to safely use "auto" in the case template class?
Topic archived. No new replies allowed.