gpt4 book ai didi

c++ - 在集合中的每个元素上调用打印的通用算法

转载 作者:太空宇宙 更新时间:2023-11-04 14:11:05 25 4
gpt4 key购买 nike

编写模板函数时:

template<class T> void print(T const & collection)

当遍历集合并取消引用迭代器时,如果你有类似 vector<int> 的东西,一切正常。除非你把它改成 vector<int*> .在不重复代码的情况下处理单个模板函数中的差异的最佳方法是什么?

最佳答案

我会编写一个模板函数 do_print 委托(delegate)给类模板 printer。类模板是一个执行 pretty-print 的函数对象,您可以通过简单地调用 *t 上的 pretty-print 版本来部分专门化 T*

因此,没有重复 pretty-print 代码,也没有编写两个轻量级实现类的轻微不便(任何现代编译器都会优化它们,因此没有运行时开销)。

我更喜欢这个解决方案而不是 SFINAE 技巧,因为部分类特化比函数重载技巧给你更多的控制(和更好的错误消息)。它也是 Alexandrescu & Sutter 编码标准推荐的。

顺便说一句,此代码也适用于 T**,因为 T* 的特化委托(delegate)给了 T 的代码。所以 T** 被发送到 T*,最后发送到 T。事实上,任意级别的间接都减少到打印指针指向的元素。

#include <iostream>
#include <vector>

namespace detail {

template<typename T>
struct printer
{
void operator()(T const& t)
{
std::cout << t; // your pretty print code here
}
};

template<typename T>
struct printer<T*>
{
void operator()(T const* t)
{
printer<T>()(*t); // delegate to printing elements (no duplication of prettty print)
}
};

}

template<typename T>
void do_print(T const& t)
{
detail::printer<T>()(t);
}

template<typename C>
void print(C const& collection)
{
for(auto&& c: collection)
do_print(c);
std::cout << "\n";
}

int main()
{
int a = 1;
int b = 2;

auto c = &a;
auto d = &b;

std::vector<int> v1 { a, b };
std::vector<int*> v2 { c, d };
std::vector<int**> v3 { &c, &d };

print(v1);
print(v2);
print(v3);
}

Live Work Space 上输出

关于c++ - 在集合中的每个元素上调用打印的通用算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14300056/

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