[英]How to specialize function template for a container?
I have function template that implements storing POD into stream: 我有实现将POD存储到流中的功能模板:
template<typename T>
void dumps(std::ostream &os, const T &t)
{
os.write(reinterpret_cast<const char *>(&t), sizeof(t));
}
Is there a way to specialize this template for containers to store container size and then call general implementation for container items? 有没有一种方法可以专门针对容器使用此模板来存储容器大小,然后调用容器项目的常规实现?
This works for std::vector
, std::set
, and std::list
. 这适用于
std::vector
, std::set
和std::list
。 Haven't tested for any other container. 没有测试任何其他容器。
It also works for POD types. 它也适用于POD类型。 Tested with
int
and the following struct
. 用
int
和以下struct
测试。
struct A
{
int a;
double b;
};
// Forward declaration of the wrapper function.
template<typename T>
void dumps(std::ostream &os, const T &t);
// Implementation for POD types
template<typename T>
void dumps(std::ostream &os, const T &t, std::true_type)
{
os.write(reinterpret_cast<const char *>(&t), sizeof(t));
}
// Implementation for container types
template<typename T>
void dumps(std::ostream &os, const T &t, std::false_type)
{
auto size = std::distance(t.begin(), t.end());
os.write(reinterpret_cast<const char *>(&size), sizeof(size));
for ( auto const& item : t)
{
dumps(os, item);
}
}
// Implementation of the wrapper function.
template<typename T>
void dumps(std::ostream &os, const T &t)
{
dumps(os, t, std::integral_constant<bool, std::is_pod<T>::value>());
}
You just need to specialise the template for each container type. 您只需要针对每种容器类型专门设计模板。 For example, with a vector.
例如,带有向量。
template<typename T>
void dumps(std::ostream &s, const typename std::vector<T> &t)
{
auto size = t.size();
s.write(<reinterpret_cast<const char *>(&size), sizeof(size);
for (auto const &item : t)
dumps(s, item); // using your dumps() for POD types
}
or (before C++11) 或(在C ++ 11之前)
template<typename T>
void dumps(std::ostream &s, const typename std::vector<T> &t)
{
typename std::vector<T>::size_type size = t.size();
s.write(<reinterpret_cast<const char *>(&size), sizeof(size);
for (std::vector<T>::const_iterator item = t.begin(), end = t.end();
i != end; ++i)
dumps(s, *item); // using your dumps() for POD types
}
Similarly, specialise for other container types. 同样,专门处理其他容器类型。 Then it will also work for containers of containers.
然后,它也将用于容器的容器。
Aside: this does assume you won't instantiate your templates for non-POD types. 除了:这确实假设您不会为非POD类型实例化模板。 It is probably worth enforcing that (although I'll leave it as an exercise).
可能值得强制执行(尽管我将其保留为练习)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.