2013-06-24 4 views
12

इस सी ++ 1 वर्ष कोड (LIVE EXAMPLE) पर विचार करें:मैं एक फ़ंक्शन कैसे घोषित करूं जिसका रिटर्न प्रकार घटाया जाता है?

#include <iostream> 

auto foo(); 

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

auto foo() { 
    return 1234; 
} 

संकलक (जीसीसी 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] 

तो तथ्य यह है कि आप इसका इस्तेमाल करने से पहले इसे परिभाषित किया गया था यह त्रुटि के लिए कारण बनता है।

संबंधित मुद्दे