2013-08-02 133 views
2

我正在閱讀「加速C++」一書的第8章。 8.3節是關於輸入和輸出迭代器:輸入迭代器的值初始化

vector<int> v; // read ints from the standard input and append them to v 
copy(istream_iterator<int>(cin), istream_iterator<int>(), back_inserter(v)); 

[...]

The second argument to copy creates a default (empty) istream_iterator, which is not bound to any file. The istream_iterator type has a default value with the property that any istream_iterator that has reached end-of-file or is in an error state will appear to be equal to the default value. Therefore, we can use the default value to indicate the "one-past-the-end" convention for copy.

這是我的理解:istream_iterator是一個模板類,並istream_iterator < int>的是模板的一個實例。寫入istream_iterator < int>()觸發istream_iterator對象的值初始化,這意味着零初始化+調用隱式默認構造函數(http://en.cppreference.com/w/cpp/language/value_initialization)。我認爲istream_iterator < INT的默認初始化>對象將工作,以及(觸發器調用默認的構造函數),所以我想這:

vector<int> v; // read ints from the standard input and append them to v 
copy(istream_iterator<int>(cin), istream_iterator<int>, back_inserter(v)); 

但是,這並不編譯:

error: expected primary-expression before ‘,’ token

我不明白髮生了什麼事。歡迎任何解釋。

回答

2

有沒有辦法默認初始化,而不是初始化值臨時。儘管表達式type()創建了一個初始化值的臨時值,但僅僅一個類型名稱不是有效的表達式。然而,對於聲明默認構造函數的任何類型(比如這個),默認初始化和值初始化是等價的;在調用非隱式構造函數之前不存在零初始化。

0

istream_iterator是一個 「模板」 類 Provides two constructor :

basic_istream<charT,traits>* in_stream; 
    istream_iterator() : in_stream(0) {} 
    istream_iterator(istream_type& s) : in_stream(&s) { ++*this; } 

默認的構造函數初始化in_stream以用於

所以最終的流0

istream_iterator<int>需要()爲EOF

修復: - copy(istream_iterator<int>(cin), istream_iterator<int>(), back_inserter(v));

2

在這種情況下:

copy(istream_iterator<int>(cin), istream_iterator<int>, back_inserter(v)); 
//        ^^^^^^^^^^^^^^^^^^^^^ 

第二個參數,istream_iterator<int>被解析爲一個類型。你需要一個實例,所以你需要(),有或沒有參數。同樣的道理,以下方法將不起作用:

void foo(int); // function declaration 

int main() 
{ 
    foo(int); 
} 
2

不要被模板分心。任何類型名稱都會出現同樣的問題:

struct S {}; 

void f(int, S); 

f(1, S); // error: S is not an object 
f(1, S()); // okay: S() constructs an object