e******o 发帖数: 757 | 1 如果要写一个template function, 比如
template //It 是一个pointer 或iterator,
void foo(It, iter)
{
//
? a = *iter;
//
}
那么应该怎样定义 a. | f*****e 发帖数: 2992 | 2 试试
auto a = *iter;
【在 e******o 的大作中提到】 : 如果要写一个template function, 比如 : template //It 是一个pointer 或iterator, : void foo(It, iter) : { : // : ? a = *iter; : // : } : 那么应该怎样定义 a.
| t****t 发帖数: 6806 | 3 if you are not using c++11 (i.e. "auto a=*iter" doesn't work), you can try:
typename std::iterator_traits::value_type a=*iter;
if It is really iterator or pointer.
【在 e******o 的大作中提到】 : 如果要写一个template function, 比如 : template //It 是一个pointer 或iterator, : void foo(It, iter) : { : // : ? a = *iter; : // : } : 那么应该怎样定义 a.
| c*******y 发帖数: 1630 | 4 good, works for both
/usr/include/c++/4.6.3/bits/stl_iterator_base_types.h
/// Partial specialization for pointer types.
template
struct iterator_traits<_Tp*>
{
typedef random_access_iterator_tag iterator_category;
typedef _Tp value_type;
typedef ptrdiff_t difference_type;
typedef _Tp* pointer;
typedef _Tp& reference;
};
/// Partial specialization for const pointer types.
template
struct iterator_traits
{
typedef random_access_iterator_tag iterator_category;
typedef _Tp value_type;
typedef ptrdiff_t difference_type;
typedef const _Tp* pointer;
typedef const _Tp& reference;
};
【在 t****t 的大作中提到】 : if you are not using c++11 (i.e. "auto a=*iter" doesn't work), you can try: : typename std::iterator_traits::value_type a=*iter; : if It is really iterator or pointer.
| t****t 发帖数: 6806 | 5 since you are using 4.6, i suggest you enable c++11 mode and use "auto",
which is much much cleaner...
【在 c*******y 的大作中提到】 : good, works for both : /usr/include/c++/4.6.3/bits/stl_iterator_base_types.h : /// Partial specialization for pointer types. : template : struct iterator_traits<_Tp*> : { : typedef random_access_iterator_tag iterator_category; : typedef _Tp value_type; : typedef ptrdiff_t difference_type; : typedef _Tp* pointer;
| e******o 发帖数: 757 | 6 thanks very much. I just tried, and it did work. |
|