gpt4 book ai didi

c++ - 模板打印函数 C++

转载 作者:太空狗 更新时间:2023-10-29 19:56:18 25 4
gpt4 key购买 nike

到目前为止我是这样写的:

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

最佳答案

删除 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);
}
}

关于c++ - 模板打印函数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52206675/

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