大佬教程收集整理的这篇文章主要介绍了c – 标准库容器的通用函数模板,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
template<class Container> void ContainerWork(const container& C) { for(const auto& elem : C) { /* convert to String and store*/ } }
然后有必要为值类型为std :: String的容器@L_874_3@特化,并将代码转换为:
template<typename T,template<typename,typename> class Container,class Allocator> void ContainerWork(Container<T,Allocator> C) { for(const T& elem : C) { /* convert to String and store*/ } } template<template<typename,class Allocator> void ContainerWork(Container<std::string,Allocator> C) { for(const std::string& elem : C) { /* frame elem in quotes*/ } }
它工作得很好,但现在我只能使用有序的容器(矢量,列表等),但我也想使用set和unordered_set.任何想法如何没有“复制粘贴”实现4个容器的容器?我正在尝试使用decltype(Container):: value_type但没有运气.
您可以更改核心功能以处理迭代器而不是容器.这将需要部分特化,这对于函数模板是不存在的,因此我们将使用委托到类的技巧:
template <typename It> void DoIteratorWork(It start,It end) { DoIteratorWork_Impl<It,typename std::iterator_Traits<It>::value_type>::call(start,end); } template <typename It,typENAME valueType> struct DoIteratorWork_Impl { static void call(It start,It end) { for (; start != end; ++start) { // operate on *it } } }; template <typename It> struct DoIteratorWork_Impl<It,std::string> { static void call(It start,It end) { for (; start != end; ++start) { // operate on *it } } };
template <class Container> void DoContainerWork(const container& C) { using std::begin; using std::end; // enable ADL of begin and end return DoIteratorWork(begin(C),end(C)); }
以上是大佬教程为你收集整理的c – 标准库容器的通用函数模板全部内容,希望文章能够帮你解决c – 标准库容器的通用函数模板所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。