【发布时间】:2017-01-17 18:25:43
【问题描述】:
我正在努力加快“现代”C++ 的速度,尤其是使用模板。我有一个覆盖
我的问题 - 有没有办法为多种容器类型编写类似于下面代码的模板?
template <typename T>
std::ostream& operator <<(ostream& os, const vector<T>& v)
{
os << "\n";
for( auto x : v ) { os << "\n\t" << x; }
os << "\n";
return os;
}
只要 T 有
我也意识到,以通用方式为所有类型覆盖容器的输出可能是一个坏主意(或至少是粗鲁的)。所以最终上面的模板代码将类型名硬编码/限制为“Point”和一个模板化容器。
好的,根据 AndyG 的建议,我有以下完整代码:
#include <iostream>
#include <map>
#include <vector>
using namespace std;
struct Point {
double x, y, z;
Point() : x(0), y(0), z(0) {};
Point(double a, double b, double c) : x(a), y(b), z(c) {}
Point(double a[]) : x(a[0]), y(a[0]), z(a[0]) {}
friend std::ostream& operator <<(ostream& os, const Point&p)
{
os << p.x << ", " << p.y << ", "<< p.z;
return os;
}
};
template <template<class> class C, class... T>
std::ostream& operator <<(ostream& os, const C<T...>& v)
{
os << "\n";
for( auto x : v ) { os << "\n\t" << x; }
os << "\n";
return os;
}
vector<Point> vp = { { 1, 2, 3 },
{ 5, 7, 4 },
{ 8, 2, 5 }
};
int main(int argc, char* argv[])
{
cout << vp[0]; // works
cout << vp; // dosen't work,
}
但仍然没有运气。编译器无法将 operator
在我的第一篇文章之前,我尝试了template <template> 的许多变体,结果大致相同。我可以得到一个可以编译的模板,但是编译器无法匹配运算符函数并使用该模板。
我不知道可变参数模板包,这显然是个好主意,但不能解决问题。
【问题讨论】:
-
template <template<class> class C, class... T> std::ostream& operator <<(ostream& os, const C<T...>& v)但你肯定会遇到一些问题。像std::map这样的关联容器很难与像std::vector这样的非关联容器混在一起 -
此处描述了类似的工作:stackoverflow.com/questions/4850473/…
-
而且,正如你所说,添加一个匹配所有 T 的模板是非常粗鲁的,包括我的类型。这就是
std::vector还没有的原因之一。 -
是的,这确实是一个相当蹩脚的用例并且存在问题。然而,我真正想做的是了解我理解的和我不理解的。