2013-06-24 55 views
12

考慮這個C++ 1Y代碼(LIVE EXAMPLE):如何聲明返回類型被推導出來的函數?

#include <iostream> 

auto foo(); 

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

auto foo() { 
    return 1234; 
} 

編譯器(GCC 4.8.1)慷慨地拍攝出這樣的錯誤:

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

我如何前瞻性聲明foo()在這裏?或者更合適,是否可以提前申報foo()


我也試着編譯代碼,我試圖在.h文件中聲明foo()定義foo()就像一個.cpp文件上面的一個,包括在我main.cpp文件中包含.hint main()通話到foo(),並構建它們。

發生同樣的錯誤。

+0

你確定你確實需要嗎?我認爲創建返回未定義的函數通常不是一個好主意,也許你需要返回一些抽象的高級類的實例?沒有冒犯,如果你知道你在做什麼:) – SpongeBobFan

回答

17

根據它在,N3638提出的紙,它是明確有效的這樣做。

相關片段:

[ 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 ] 

但是它接着說:

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] 

所以,你使用它,它被定義之前的事實導致其錯誤。

相關問題