質問

The standard library neglects to implement basic operations for std::set and std::map like

set<T> set<T>::getUnion(set<T> other)

and

bool map<K,V>::contains(K key)

I know there are verbose and/or indirect workarounds for these methods but if I want my code to be maximally readable and expressive, I'm going to have to inherit from the STL, write my own Set and Map classes, and implement them myself. And yes, I'm aware of the sermonizing against doing this but the fact is the STL is incomplete.

I've done this but now I can't initialize my new classes using, e.g.,

Set<int> s = {1,2,3,4};

How do I inherit these initializers from the std classes?

役に立ちましたか?

解決

Despite the fact that publically inheriting from standard library containers is considered to be a bad idea, you can "inherit" the constructors:

template <typename T>
struct Set : std::set<T>
{
  using std::set<T>::set; // "inherit" the constructors.
};

then

Set<int> s{1,6,4,3,3,9};

Note that a better approach might be to implement functions:

template <typename C>
bool contains(const C& container, const typename C::key_type& key)
{
  return container.count(key);
}

and similarly for the union of sets.

他のヒント

For gcc 4.7.x, you have to call the initializer_list constructor for the set or map:

template <typename T>
class Set : public set<T> {
public:
    Set(){
        set<T>::set();
    }
    Set(initializer_list<T> iList) {
        set<T>::set(iList);
    }
};

Allowing

Set<int> s = {1,2,3,4};

But after much trial and error, I can't find a way to do this for std::map.

Also, it disables all the other constructors, requiring me to reimplement them, a task I'm not up to yet, so I'm just giving up on initializer lists for now. Anyone is welcome to submit an answer that reimplements all the constructors as Set and I'll choose it as the answer.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top