Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - How do I declare a function whose return type is deduced?

Consider this C++1y code (LIVE EXAMPLE):

#include <iostream>

auto foo();

int main() {
    std::cout << foo();   // ERROR!
}

auto foo() {
    return 1234;
}

The compiler (GCC 4.8.1) generously shoots out this error:

main.cpp: In function ‘int main()’:
main.cpp:8:18: error: use of ‘auto foo()’ before deduction of ‘auto’
std::cout << foo();
                   ^

How do I forward-declare foo() here? Or maybe more appropriately, is it possible to forward-declare foo()?


I've also tried compiling code where I tried to declare foo() in the .h file, defined foo() just like the one above in a .cpp file, included the .h in my main.cpp file containing int main() and the call to foo(), and built them.

The same error occurred.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

According to the paper it was proposed in, N3638, it is explicitly valid to do so.

Relevant snippet:

auto x = 5;                // OK: x has type int
const auto *v = &x, u = 6; // OK: v has type const int*, u has type const int
static auto y = 0.0;       // OK: y has type double
auto int r;                // error: auto is not a storage-class-specifier
auto f() -> int;           // OK: f returns int
auto g() { return 0.0; }   // OK: g returns double
auto h();                  // OK, h's return type will be deduced when it is defined

However it goes on to say:

If the type of an entity with an undeduced placeholder type is needed to determine the type of an expression, the program is ill-formed. But once a return statement has been seen in a function, the return type deduced from that statement can be used in the rest of the function, including in other return statements.

auto n = n;            // error, n's type is unknown
auto f();
void g() { &f; }       // error, f's return type is unknown
auto sum(int i) {
  if (i == 1)
    return i;          // sum's return type is int
  else
    return sum(i-1)+i; // OK, sum's return type has been deduced
}

So the fact that you used it before it was defined causes it to error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...