请尝试以下
#include <iostream>
#include <vector>
#include <cstring>
template <class T>
std::ostream & print(T &c, std::ostream &os = std::cout)
{
for (auto x : c) os << x << ' ';
os << std::endl;
return os;
}
template <class T, size_t N>
std::ostream & print(T (&a)[N], std::ostream &os = std::cout)
{
for (auto x : a) os << x << ' ';
os << std::endl;
return os;
}
template <class T>
std::ostream & print(T *a, size_t n, std::ostream &os = std::cout)
{
for (auto p = a; p != a + n; ++p) os << *p << ' ';
os << std::endl;
return os;
}
int main()
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
double b[] = { 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 };
char s[] = "Hello zooombini";
std::vector<int> v1(a, a + sizeof(a)/sizeof(*a));
std::vector<double> v2(b, b + sizeof(b)/sizeof(*b));
print(a);
print(b);
print(v1);
print(v2);
print(s, std::strlen(s));
return 0;
}
输出是
0 1 2 3 4 5 6 7 8 9
0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
0 1 2 3 4 5 6 7 8 9
0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
H e l l o z o o o m b i n i
甚至可以添加更多的重载函数
#include <iostream>
#include <vector>
#include <cstring>
template <class T>
std::ostream & print(T &c, std::ostream &os = std::cout)
{
for (auto x : c) os << x << ' ';
os << std::endl;
return os;
}
template <class T, size_t N>
std::ostream & print(T (&a)[N], std::ostream &os = std::cout)
{
for (auto x : a) os << x << ' ';
os << std::endl;
return os;
}
template <class T>
std::ostream & print(T *a, size_t n, std::ostream &os = std::cout)
{
for (auto p = a; p != a + n; ++p) os << *p << ' ';
os << std::endl;
return os;
}
std::ostream & print(const char *s, std::ostream &os = std::cout)
{
return os << s << std::endl;
}
std::ostream & print(char *s, std::ostream &os = std::cout)
{
return os << s << std::endl;
}
int main()
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
double b[] = { 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 };
int *p = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
char s[] = "Hello zooombini";
std::vector<int> v1(a, a + sizeof(a)/sizeof(*a));
std::vector<double> v2(b, b + sizeof(b)/sizeof(*b));
print(a);
print(b);
print(p, 10) << std::endl;
print(v1);
print(v2);
print(s, std::strlen(s));
print(s);
delete []p;
return 0;
}
输出是
0 1 2 3 4 5 6 7 8 9
0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
H e l l o z o o o m b i n i
Hello zooombini
副本可能无论如何都会被删除 – 4pie0 2014-09-26 11:21:10
@ 0d0a为什么依靠可能?在很多情况下它不会。 (事实上,我不能认为任何情况下,它不会复制) – 2014-09-26 11:21:38
不依赖于可能,只是知道它可能会被删除,这只是信息 – 4pie0 2014-09-26 11:22:29