Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

c++ - `auto` return type in context of class members

How can automatic type deduction be used for class members? For example, the following code

struct A
{
  auto foo(); // foo is defined in another file 
};


int main()
{
  A a;
  a.foo();
}

where foo has the return type auto results in the following error:

error: function 'foo' with deduced return type cannot be used before it is defined
  a.foo();
    ^

The error is comprehensible since the compile cannot know what foo's return type is without knowing its definition.

My question is, if there is any workaround or some kind of programming pattern to circumvent the problem that auto return type cannot be used for class member functions, in case that the function's declaration and definition is separated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to use return type deduction, you cannot separate the declaration and definition into different files (not unless everyone includes both). There's no workaround for this other than to use an actual type.

When C++ goes to compile code that calls func, it must be able to know, at that time, what it will return. Without having definition in that translation unit, the compiler cannot know what will be returned. And therefore, the compiler cannot compile that code. And C++'s compilation model does not allow it to use information from other translation units in this way.

The best you might be able to do is wait for modules, which may be able to get around this.

Don't think of return type deduction as a way to never have to write return types. It's a feature intended for circumstances where the return type is awkward to write, where the most reasonable way to write it is as a decltype(expr), and expr is the exact expression you're going to return. And those cases are typically in template code, which has to go into headers anyway. If the return type is simple and obvious to you, there's really little reason not to put it there. Don't use return type deduction by default.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...