gpt4 book ai didi

c++ - 包装 STL 以扩展

转载 作者:太空狗 更新时间:2023-10-29 23:53:14 24 4
gpt4 key购买 nike

所以我读到从 STL 继承是个坏主意。但是如何将 STL 类包装在其他类中以扩展它们呢?这样做的主要目的是分离抽象级别等。

类似于:

template<class T>
class MyVector{
public:
T& last(){
return data[data.size() - 1]
}

bool include(T& element);

//etc.

private:
vector<T> data;
}

这是个好主意吗?这是 C++ 程序员经常做的事情吗?

谢谢。

最佳答案

是的,包装优于继承,但前提是您需要将状态添加到现有数据结构中。否则,添加非成员函数。这在 C++ 编码标准 ( Amazon ) 的第 35 项中有更详细的解释

To add state, prefer composition instead of inheritance. Admittedly, it's tedious to have to write passthrough functions for the member functions you want to keep, but such an implementation is vastly better and safer than using public or nonpublic inheritance.

template<typename T>
class MyExtendedVector
{
public:
// pass-through functions for std::vector members
void some_existing_fun() { return vec_.some_existing_fun(); }

// new functionality that uses extra state
void some_new_fun() { // your implementation here }

private:
std::vector<T> vec_;
// extra state e.g. to do logging, caching, or whatever
};

To add behavior, prefer to add nonmem-ber functions instead of member functions.

但是请确保您的算法尽可能通用:

// if you CAN: write algorithm that uses iterators only 
// (and delegates to iterator category that container supports)
template<typename Iterator, typename T>
bool generic_contains(Iterator first, Iterator last, T const& elem)
{
// implement using iterators + STL algorithms only
return std::find(first, last, elem) != last;
}

// if you MUST: write algorithm that uses specific interface of container
template<typename T>
void vector_contains(std::vector<T> const& v, T const& elem)
{
// implement using public interface of Container + STL algorithms
return generic_contains(v.begin(), v.end(), elem);
}

关于c++ - 包装 STL 以扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11941670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com