gpt4 book ai didi

c++ - STL 扩展/修改最佳实践

转载 作者:行者123 更新时间:2023-11-30 05:28:30 26 4
gpt4 key购买 nike

我已经用 C++ 编写了几个月,现在我对它已经足够满意了,可以开始实现我自己的库,其中包含我发现自己一次又一次重复使用的东西。困扰我的一件事是,您总是必须为 std::accumulatestd::fill 等函数提供开始和结束迭代器...

完全没有提供合格容器的选项,一遍又一遍地写开始和结束简直是一件烦人的事。所以,我决定将这个功能添加到我的库中,但是我遇到了问题,我想不出这样做的最佳方法。以下是我的一般解决方案:

<强>1。宏

- 封装了整个函数调用的宏
前任。 QUICK_STL(FCall)

- 采用容器、函数名称和可选参数的宏
前任。 QUICK_STL(C,F,Args...)

<强>2。包装函数/仿函数

- 采用容器、函数名称和可选参数的类
前任。 quick_STL(F, C, Args...)

<强>3。重载函数

- 重载命名空间 std 或我的库命名空间
中的每个函数例如

namespace std { // or my library root namespace 'cherry' 
template <typename C, typename T>
decltype(auto) count(const C& container, const T& value);
}



我通常避开宏,但在这种情况下它肯定可以节省很多编写的代码行数。关于函数重载,我想使用的每个函数都必须重载,这不会真正扩展。不过,这种方法的好处是您可以保留函数的名称。通过完美的转发和decltype(auto) 重载变得容易很多,但仍然需要时间来实现,并且如果添加另一个函数则必须进行修改。至于我是否应该重载 std 命名空间,我很怀疑在这种情况下它是否合适。

在 STD 命名空间中重载函数的最合适方法是什么(请注意,这些函数将仅用作原始函数的代理)?

最佳答案

你需要阅读这个:Why do all functions take only ranges, not containers?

还有这个:STL algorithms: Why no additional interface for containers (additional to iterator pairs)?

I have been writing in c++ for a few months, and i am comfortable enough with it now to begin implementing my own library...

让我往好的方面看,然后说......我们中的一些人以前去过那里...... :-)

One thing that nagged me was the fact that you always had to provide a beginning and end iterator for functions like std::accumulate,std::fill etc...

这就是为什么你有 Boost.Ranges和 Eric 的提议 ranges这似乎不会进入 C++17。

  1. Macros

参见 Macros

  1. Wrapper Function/Functor

还不错......只要你做得正确,你就可以做到,这就是 Ranges 对容器所做的本质......参见上述实现

  1. Overload Functions

    • Overload every function in namespace std ...

不要那样做...C++ 标准不喜欢它。

看看标准怎么说

$17.6.4.2.1 The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

关于c++ - STL 扩展/修改最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36813760/

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