是否可以推断出 std::insert_iterator 的包含类型
Is it possible to deduce the contained type for std::insert_iterator?
我有一个函数,它需要一个模板化的迭代器类型。
它当前取消引用迭代器以检查正在迭代的类型。
template < typename Iterator >
void func( Iterator i )
{
// Inspect the size of the objects being iterated
const size_t type_size = sizeof( *i );
...
}
我最近发现几种标准迭代器类型,例如std::insert_iterator
将*i
定义为对i
的引用。
也就是说,迭代器本身的大小sizeof(*i)
;与sizeof(i)
或sizeof(***i)
相同
是否有一种通用方法(支持C++ 03)来确定任何标准迭代器正在迭代的对象的大小或类型?
这就是
iterator_traits
的用途。
typedef typename std::iterator_traits<Iterator>::value_type type;
const std::size_t type_size = sizeof(type);
编辑:这不适用于所有输出迭代器。
我不确定为什么你想要输出迭代器的value_type
,因为无法从输出迭代器中提取值。但是,三个插入迭代器适配器都value_type
定义为void
并提供container_type
类型成员,因此如果T
的value_type
结果是void
,则可以回退到T::container_type
value_type
。
(我所说的"value_type
"是指std::iterator_traits<T::container_type>::value_type
和std::iterator_traits<T>::value_type
。
或者,您可以不尝试使用输出迭代器,就好像它们具有值:)
编辑:SFINAE不是必需的:(即使没有C++11的美好)
template<typename U, typename T> struct helper {typedef U type;};
// ostream*_iterator handling courtesy Drew Dormann
template <typename T, typename charT, typename traits>
struct helper<void, std::ostream_iterator<T, charT, traits> > {typedef T type;};
template <typename charT, typename traits>
struct helper<void, std::ostreambuf_iterator<charT, traits> > {typedef charT type;};
// std::raw_storage_iterator still needs an override
// as well as any non-standard output iterators which don't define a container_type.
template<typename T> struct helper<void, T>
{typedef typename std::iterator_traits<typename T::container_type>::value_type type;};
typedef<typename It> struct my_value_type
: public helper<typename std::iterator_traits<It>::value_type, It> {};
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 编译包含字符串的代码时遇到问题
- c++库的公共头文件中应该包含什么
- 将包含C样式数组的对象初始化为成员变量(C++)
- 是否需要删除包含对象的"pair"?
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 使用mongocxx驱动程序时包含头文件问题
- 如何在h文件中包含.o对象文件
- 在混合代码库中将C转换为C++时出现许多包含错误
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- cmath抛出错误C2062、C2059、C2143和C2447.cmath包含在矢量文件中
- 为什么您需要C++头文件的包含保护
- 无法在UE4中包含BP类到CPP类
- g++ 说函数不存在,即使包含正确的标头
- 在C++代码中包含opencv时,使用ctypes创建.so文件
- Visual C++GC接口如何启用它以及要包含哪个库
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)