我在 C++ 中有一个模板函数,它序列化一个可迭代对象:
template<typename Stream, typename Iter, typename Infix, typename Closure>
inline Stream &stream_iterable(Stream &os, Iter from, Iter to, Infix infix_, Closure open, Closure close) {
if (from == to) return os;
os << open << *from;
for (++from; from != to; ++from) {
os << infix_ << *from;
}
os << close;
return os;
}
例如,它基本上转换std::vector<int>{1,2}
到一个字符串 "[1,2]"
我想检查迭代器指向的对象类型,如果它是 std::string
, 我想用 std::quoted
在 vector 的元素周围添加引号,像这样:
template<typename Stream, typename Iter, typename Infix, typename Closure>
inline Stream &steam_iterable_quoted(Stream &os, Iter from, Iter to, Infix infix_, Closure open, Closure close) {
if (from == to) return os;
os << open << std::quoted(*from);
for (++from; from != to; ++from) {
os << infix_ << std::quoted(*from);
}
os << close;
return os;
}
如何检查 (*from) 的类型并将这两个函数合二为一?
最佳答案
您实际上不需要知道 stream_iterable
主体中的类型。俗话说,加一层间接:
namespace detail {
template<typename T>
constexpr T const& prepare_to_print(T const& t) { return t; }
auto prepare_to_print(std::string const s&) { return std::quoted(s); }
// A non-const overload would be required as well...
// Forwarding can be a drag sometimes
}
只需将取消引用的迭代器传递给 prepare_to_print
。重载的好处是您可以通过稍后添加更多重载来进一步自定义行为。
关于c++ - 如何确定迭代器在 C++ 模板函数中指向的对象的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51023795/