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

后端 未结 1 400
星月不相逢
星月不相逢 2020-12-17 14:55

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

#include 

auto foo();

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

a         


        
相关标签:
1条回答
  • 2020-12-17 15:40

    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.

    0 讨论(0)
提交回复
热议问题