到目前为止,我写了以下内容:
template <typename TType>
void print_vector(const std::vector<TType>& vec)
{
typename std::vector<TType>::const_iterator it;
std::cout << "(";
for(it = vec.begin(); it != vec.end(); it++)
{
if(it!= vec.begin()) std::cout << ",";
std::cout << (*it);
}
std::cout << ")";
}
template<>
template <typename T2>
void print_vector(const std::vector< std::vector<T2> >& vec)
{
for( auto it= vec.begin(); it!= vec.end(); it++)
{
print_vector(*it);
}
}第一个函数适用于std::vector< double>之类的东西。现在,我还希望能够打印std::vector< std::vector< TType>>内容。第二部分没有编译,但这是我解决任务的“想法”。对于如何实现这种行为,有什么建议吗?
Compilation Error: too many template-parameter-lists
发布于 2018-09-06 22:45:41
删除template<>部件,函数模板重载将正常工作。
template <typename TType>
void print_vector(const std::vector<TType>& vec)
{
typename std::vector<TType>::const_iterator it;
std::cout << "(";
for(it = vec.begin(); it != vec.end(); it++)
{
if(it!= vec.begin()) std::cout << ",";
std::cout << (*it);
}
std::cout << ")";
}
template <typename T2>
void print_vector(const std::vector< std::vector<T2> >& vec)
{
for( auto it= vec.begin(); it!= vec.end(); it++)
{
print_vector(*it);
}
}发布于 2018-09-06 23:01:24
您可能实际上想要一个更通用的问题解决方案,允许打印几乎任何可迭代的类型:
#include <vector>
#include <iostream>
template <typename Iterable>
std::ostream& operator<<(std::ostream& os, const Iterable& vals)
{
for (const auto& val : vals)
os << val << std::endl;
return os;
}
int main()
{
auto simple_vec = std::vector<int>{3, 5 , 7};
std::cout << simple_vec;
auto nested_vec = std::vector<std::vector<int>>{{1, 2}, {3, 4}};
std::cout << nested_vec;
}对于这个解决方案的进一步改进,您可以尝试使用SFINAE,以确保模板化的<<仅可用于可迭代类型。
发布于 2018-09-06 22:58:01
如果你让你的函数打印基类型并使用自身递归覆盖向量:
template<typename T>
void print( const T &t )
{
std::cout << t;
}
template<typename T>
void print( const std::vector<T> &v )
{
std::cout << '[';
for( auto it = v.begin(); it != v.end(); ++it ) {
if( it != v.begin() ) std::cout << ',';
print( *it );
}
std::cout << ']';
}这样就不需要为向量的向量或向量的向量等编写特殊的向量。
https://stackoverflow.com/questions/52206675
复制相似问题