2015-11-09 18 views
4

讓我們來看看下面的下面的代碼C++ 14種標準說:什麼關於汽車的參數類型

#include <iostream> 

class Test 
{ 
private: 
    int x; 
public: 
    Test(int _x) : 
     x(_x) 
    { 
     std::cout << "Im being constructed" << std::endl; 
    } 

    int getx() 
    { 
     return this->x; 
    } 

    friend std::ostream& operator<<(std::ostream& os, Test& other) 
    { 
     os << other.getx(); 
     return os; 
    } 
}; 

auto func(auto x) 
{ 
    std::cout << x << std::endl; 
    return x.getx(); 
} 

int main() 
{ 
    auto y = func(20); 

    return 0; 
} 

編譯器如何決定是否(20)應該是一個int或測試對象? Test的構造函數並不明確,因此標準對此有何評論?

+4

1.'auto'作爲參數是概念ts的一部分。 2.'x'被推斷爲'int',而不是'Test' –

+1

[gcc接受自動參數,即使它是概念的一部分 - 精簡版](http://stackoverflow.com/questions/30665506/auto-not-allowed -in-function-prototype-with-clang/30665723#30665723)雖然如果你使用'-pedantic',gcc會警告這不是iso C++。 –

+0

好的,謝謝你,所以標準允許使用lambdas自動運行,但不是函數,我是否正確? – Mamma

回答

5

所以,雖然GCC允許汽車在功能參數這不是C++ 14的一部分,但根據香草薩特的最後一趟報告concepts-litemay become part of C++1z一部分。

我相信,海灣合作委員會允許以此爲延伸,如果我們編譯使用-pedantic GCC會警告你的程序:

warning: ISO C++ forbids use of 'auto' in parameter declaration [-Wpedantic] 
auto func(auto x) 
     ^
從概念精簡版的建議

因此,我們可以看到:

auto func(auto x) 
{ 
    std::cout << x << std::endl; 
    return x.getx(); 
} 

是相當於:

template <typename T1> 
auto func(T1 x) 
{ 
    std::cout << x << std::endl; 
    return x.getx(); 
} 

因此x w否則推定爲int。編譯器會理所當然地讓你像下面這樣一個從海灣合作委員會(see it live)錯誤:

error: request for member 'getx' in 'x', which is of non-class type 'int' 
    return x.getx(); 
       ^

這是包括在建議部分5.1.1[dcl.fct]

的在參數聲明子句 中使用auto或概念名稱應解釋爲使用具有相同約束條件和指定概念的類型參數。 [注意: 達到此目的的確切機制未詳細說明。末端注] [實施例:下面聲明

auto f(auto x, const Regular& y); 

通用 函數等效於以下聲明

template<typename T1, Regular T2> 
    auto f(T1 x, const T2&); 

末端示例]

+0

乾杯隊友,你和Piotr Skotnicki爲我提供了很好的答案。 – Mamma