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.
}

車への共有ポインタをconst車への共有ポインタにキャストせずにこれは可能ですか?

4

2 に答える 2

8

Boost.Range「間接」アダプターの適切な使用例のように聞こえます。

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

ここでデモコードを動作させます。

于 2013-04-26T19:38:24.867 に答える
2

車への共有ポインタを const 車への共有ポインタにキャストせずにこれは可能ですか?

いいえ、できません。はconst、それが参照するものではなく、共有ポインターに適用されます。

これは間接参照の基本的な事実であり、ポインターでも同じです。

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

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

反復で本質的に不変性を得る方法がないことは間違いなく残念ですが、それは間接化を採用しているためですCar

于 2013-04-26T19:25:19.397 に答える