c++ - 从 std::set 或 std::map 继承初始化语法

标签 c++ stl

标准库忽略了实现std::setstd::map 的基本操作

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

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

我知道这些方法有冗长和/或间接的解决方法,但如果我希望我的代码具有最大的可读性和表现力,我将不得不从 STL 继承,编写我自己的 SetMap 类,并自己实现它们。是的,我知道反对这样做的说教,但事实是 STL 是不完整的。

我已经这样做了,但现在我无法使用例如

初始化我的新类
Set<int> s = {1,2,3,4};

如何从 std 类继承这些初始化器?

最佳答案

尽管从标准库容器公开继承被认为是一个坏主意,但您可以“继承”构造函数:

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

然后

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

请注意,更好的方法可能是实现函数:

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

similarly for the union of sets .

关于c++ - 从 std::set 或 std::map 继承初始化语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23437562/

相关文章:

c++ - QPrinter 在图像周围环绕文本

c++ - 为什么 std::string 对象的最大大小是 4611686018427387897?

c++ - 编译 gcc/g++/libstdc++ 时的 --enable-threads=LIB 是什么意思?

c++ - 将函数应用于 2 个 STL vector

c++ - 使用 fscanf 读取/proc C++

c++ - 在智能指针的取消引用值上调用 std::move()

c++ - 禁止将右值引用传递给函数

c++ - 我想存储从文件中获取的数字及其计数

c++ - 什么是 C++ 的 32 位和 64 位窗口中的兼容 "int"类型?

C++运算符查找误区