且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从输出迭代器中获取值类型?

更新时间:2023-11-28 10:19:52

正确观察,输出迭代器的 value_type void 。所以除了替换它之外别无选择:

As correctly observed, the value_type of an output iterator is void. So there not much to do apart from replacing this :

typename std::iterator_traits<OutputIterator>::value_type elem;

这个

decltype(*first) elem;

(即使标准不保证它也能正常工作 - 解除引用可能会返回代理输出迭代器)。

(even though the Standard doesn't guarantee it'll work - a proxy might be returned by dereferencing an output iterator).

正如你所说的没有C ++ 11解决方案所以可能需要进行重新设计。以下是一些选项:

As you said no C++11 solution so a redesign might be needed. Here are some options:

您可以传递对容器的引用,而不是第一个元素的迭代器。看起来你想要的只是一个 push_back

Instead of an iterator to the first element, you could pass a reference to the container. It seems like all you want is a push_back.

template<template<typename,typename> class stlContainer>
void copy_container(
    MyMontainer const &cont, OutputIterator first) 
{ 
    // insertion in stlContainer

然后您需要的是一层特征,以便调度到每个容器的正确插入实现

then all you need is a layer of traits to dispatch to the right implementation of insertion per container

值类型可以是额外的模板参数。

The value type could be an extra template parameter.

template<typename value_type, typename OutputIterator>
void copy_container(MyMontainer const &cont, OutputIterator first) 
{
    value_type elem;
...