在不使用部分模板函数特化的情况下对递归的 std::vector<std::vector<...>> 进行字符串化
Stringify a recursive `std::vector<std::vector<...>>` without using partial template function specialization
我寻求(例如)将...的向量字符串化(具有任意深度的嵌套)。
我尝试了以下方法:
#include <iostream>
#include <sstream>
#include <vector>
template<typename E>
std::string toString(const E& element) {
std::ostringstream oss;
oss << element;
return oss.str();
}
template<typename E>
std::string toString<std::vector<E>>(const std::vector<E>& set) {
std::ostringstream oss;
oss << "{";
bool started = false;
for (const auto& el : set) {
if (started) {
oss << ",";
}
else {
started = true;
}
oss << toString(el);
}
oss << "}";
return oss.str();
}
int main()
{
std::vector<std::vector<int>> v{{1},{2,3}};
std::cout << toString(v) << std::endl; // want to output "{{1},{2,3}}"
return 0;
}
但它 generates a compiler 错误,因为部分模板函数特化显然是不允许的。这种事情我该怎么办?
这里你想要的不是模板特化而是函数重载。
用这个代替你的模板专业化方法。
template <typename E>
std::string toString(const std::vector<E>& set) {
std::ostringstream oss;
oss << "{";
bool started = false;
for (const auto& el : set) {
if (started) {
oss << ",";
}
else {
started = true;
}
oss << toString(el);
}
oss << "}";
return oss.str();
}
您的代码还有一个拼写错误:oss << toSring(el)
。
我寻求(例如)将...的向量字符串化(具有任意深度的嵌套)。
我尝试了以下方法:
#include <iostream>
#include <sstream>
#include <vector>
template<typename E>
std::string toString(const E& element) {
std::ostringstream oss;
oss << element;
return oss.str();
}
template<typename E>
std::string toString<std::vector<E>>(const std::vector<E>& set) {
std::ostringstream oss;
oss << "{";
bool started = false;
for (const auto& el : set) {
if (started) {
oss << ",";
}
else {
started = true;
}
oss << toString(el);
}
oss << "}";
return oss.str();
}
int main()
{
std::vector<std::vector<int>> v{{1},{2,3}};
std::cout << toString(v) << std::endl; // want to output "{{1},{2,3}}"
return 0;
}
但它 generates a compiler 错误,因为部分模板函数特化显然是不允许的。这种事情我该怎么办?
这里你想要的不是模板特化而是函数重载。
用这个代替你的模板专业化方法。
template <typename E>
std::string toString(const std::vector<E>& set) {
std::ostringstream oss;
oss << "{";
bool started = false;
for (const auto& el : set) {
if (started) {
oss << ",";
}
else {
started = true;
}
oss << toString(el);
}
oss << "}";
return oss.str();
}
您的代码还有一个拼写错误:oss << toSring(el)
。