2013-06-24 3 views
12

Rozważmy C++ 1r kod (LIVE EXAMPLE):Jak zadeklarować funkcję, której typ powrotu został wyprowadzony?

#include <iostream> 

auto foo(); 

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

auto foo() { 
    return 1234; 
} 

kompilator (GCC 4.8.1) hojnie trafia się taki błąd:

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

Jak przekazać zadeklarować foo() tutaj? A może bardziej stosownie, czy można przekazać dalej - deklarować foo()?


Próbowałem zostały również kod gdzie próbowałem zadeklarować foo() w pliku .h kompilacji zdefiniowane foo() podobnie jak ten powyżej w pliku .cpp, obejmowały .h w moim pliku main.cpp zawierający int main() i połączenia do foo() i je zbudował.

Wystąpił ten sam błąd.

+0

Czy jesteś pewien, że naprawdę tego potrzebujesz? Nie wydaje mi się, że generalnie dobrze jest tworzyć funkcje, które zwracają coś tak nieokreślonego, może powinieneś zwrócić instancję jakiejś abstrakcyjnej klasy wysokiego poziomu? Bez obrazy, jeśli wiesz co robisz :) – SpongeBobFan

Odpowiedz

17

Zgodnie z dokumentem, w którym został zaproponowany, N3638, jest to jednoznacznie ważne.

Odpowiedni fragment:

[ Example: 

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 
— end example ] 

Jednak mówi dalej:

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.

[ Example: 

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 
} 
—end example] 

więc fakt, że można go stosować, zanim została zdefiniowana powoduje błędu.

Powiązane problemy