c++ - 如何确定迭代器在 C++ 模板函数中指向的对象的类型?

标签 c++ templates vector c++14

我在 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/

相关文章:

vector - Rust 泛型向量<Vector<T>>

c++ - 将二维整数数组(与图像相关)调整为特定大小?

c++ - Gsoap编译

c++ - 如何在模板化转换运算符中消除这种构造的歧义?

c++ - 参数包扩展遇到问题

for-loop - APL 编程 - 为向量赋值

c++ - .out 将 -c 指令与 g++ 一起使用时权限被拒绝

Eclipse for Android NDK 中的 C++ static const 多重声明错误

c# - c++和c#之间的共享内存同步

C++基本构造函数问题