How do I overload the insert() statement so that, in addition to inserting values into multimap , a check is performed.
|
1 answer
First: get ready for non-polymorphic inheritance. At a minimum, this means that forgetting about reference through the base class.
For example, you will have this design :
template<typename Key, typename Value> class my_multimap : public std::multimap<Key, Value> { public: using Base = std::multimap<Key, Value>; using std::multimap<Key, Value>::multimap; // вытащили конструкторы using value_type = typename Base::value_type; // далее примерный код bool insert(const value_type& val) { std::cout << "my_multimap::insert(copy)\n"; if (true /* какая-то проверка */) return false; Base::insert(val); return true; } // для перемещения bool insert(value_type&& val) { std::cout << "my_multimap::insert(move)\n"; if (true /* какая-то проверка */) return false; Base::insert(std::forward<value_type>(val)); return true; } //using Base::insert; // вытащили другие методы insert [0] // А ещё поглядеть на перегрузки других методов insert: // http://www.cplusplus.com/reference/map/multimap/insert/ }; If you try this:
void foo(std::multimap<int, int> &map) { map.insert((std::make_pair(31337,31337)); // [1] } ... my_multimap<int,int> my_map; foo(my_map); then in line 1 the insert will be called not of your class, but of the base class: the class is not polymorphic, and the method is not virtual. And if you uncomment the line [0], then you also get a funny picture: a more suitable basic method will be called.
And if you create some fields in your class, which you need to release in the constructor, then deleting by the base class will also lead to a drain on resources.
So think twice before doing.
- In general, such inheritance violates LSP. So ideologically the composition is better (well, or private inheritance, if you are too lazy.) - VladD
- Depends on the situation. Sometimes a real duck needs to fasten a nameplate to his leg. To do fully a duck for this, well, there is no desire, exactly like opening up from a real duck. Nobody resists the non-polymorphic inheritance of patterns in type_traits or inheritance from boost :: noncopyable (or analogs, although you can write Foo (Foo) = delete; everywhere). But, hand on heart, it took me exactly once, and an hour later it was removed :) - Monah Tuk
- Well, a duck with a nameplate is just a good example of composition :) // Nonresistance to improper inheritance is a consequence of a problem with C ++ design, in which inheritance in the sense of “Is-A” is tightly fused with code sharing. So you have to turn a blind eye to abuse inheritance. - VladD
|
insertoption with a different signature is not suitable? typeinsert(..., bool check)? - Harry