既にコンテナへのconstのアクセスを提供する、と述べました。
コンテナを世界に公開する必要があるため、まだ完全ではないため、変更すると、インターフェイスがもはや同じでない場合でもユーザーコードも強制的に変更されます。
しかし、最後の希望があります:
あなたはラムダ(C++ 0xの)を使用することができるなら、あなたはより良いfor_eachアルゴリズムを提供したい:
class MyThingManager
{
public:
template< typename FunctorType > // note : could be non-template, in wich case use std::function<>
void modify_each_thing(FunctorType f) // if you use std::function, you can put the implementation in the cpp file instead of the header/inline
{
// do some checks, or maybe generate a list of Things that you allow to modify
// then apply the function (here we assume we don't have a separate list - implementation defined for the win!)
std::for_each(m_things.begin(), m_things.end(), f); // oh yeah
// then we can apply anything more we want
check_everything_is_still_valid();
notify_the_world();
}
// here is a simpler read-only version
template< typename FunctorType >
void for_each_thing(FunctorType f) const { std::for_each(m_things.begin(), m_things.end(), f); }
// in case you want the user to know how many things to manipulate
size_t things_count() const { return m_things;}
private:
std::vector<Thing> m_things; // could be any container, that's isolated from the algorithm!
};
使用法:
MyThingManager manager;
manager.for_each_thing([](const Thing& thing){ std::cout << "\nA thing : " << thing; });
を
const参照をベクトルに戻すことができます。そうすれば、発信者はそれを変更することはできません。 – Juho
議論から明らかなように、getVectorOfFoo()はクラスのメンバ関数であり、ベクトルはクラスのメンバ変数ですが、これは質問のどこにも記述されておらず、違いがあります。 –
良い議論は、みんなから何かを学んだ。みんなありがとう。 – Mark