2013-04-26 69 views
2

如果我有一個類,比如說,共享指針和指向的常量性對象

class Car { 
    public: 
    void Drive(); 
    void DisplayMileage() const; 
}; 

我創建基於此類別的共享指針,

typedef boost::shared_ptr<Car> CarPtr; 

然後我去填充CarPtrs的載體,

std::vector<CarPtrs> cars...; 

我現在要遍歷向量和做一些東西:

for(auto const &car : cars) { 
    car->DisplayMileage(); // I want this to be okay 
    car->Drive(); // I want the compilation to fail here because Drive isn't const. 
} 

這可能沒有將共享指針投射到共享指針到一輛車的共享指針?

+3

'boost :: shared_ptr '? – Pubby 2013-04-26 19:17:52

+0

我想對const做這個特殊的迭代失敗,我可能想在另一次迭代中改變車子。 – 2013-04-26 19:19:50

+1

http://stackoverflow.com/q/15164330/560648 http://stackoverflow.com/q/13464199/560648 – 2013-04-26 19:24:49

回答

8

聽起來像是不錯的使用情況the Boost.Range "indirected" adaptor

for(auto const& car : cars | boost::adaptors::indirected) { 
    car.DisplayMileage(); 
    car.Drive(); // error: passing 'const Car' as 'this' argument of 'void Car::Drive()' discards qualifiers [-fpermissive] 
} 

工作演示代碼here

+0

輝煌,謝謝!這正是我想在不改變原始定義的情況下做的,這是一個學術性的練習,但是很好的答案。再次感謝。 – 2013-04-26 19:43:55

+0

_非常好! – 2013-04-27 12:55:26

2

這是可能的沒有將共享指針投射到共享指針到一輛汽車

不,這是不可能的。 const適用於共享指針,而不適用於它指向的內容。

這是間接的基本事實,它與指針一樣:

int main() 
{ 
    int x = 0; 
    int* p1 = &x; 
    auto const p2 = p1; 

    // p2 is `int* const`, not `int const*` 
    *p1 = 1; 
} 

這可以說是不幸的,還有根本就沒有辦法在你的迭代本身獲得不變性,但是那是因爲你使用間接:你不是在迭代Car s。

+3

有時,我最喜歡的部分是「不,這是不可能的」答案(這非常有意義,並且是正確的!)緊接着「確定,這很容易用'boost'」答案。 – Yakk 2013-04-27 00:04:10

相關問題