In a C ++ template function, can I return the type of arguments dereferenced?

I mean the following. I want a template function that takes two vector iterators (or two pointers to an array from double) and returns double, which is somehow related to the vector iterators or pointers of the array that I pass. However, I want this to work for double or int or any arithmetic type.

I think I’m not allowed to say:

template <class T> 
T* func(T Begin, T End)

 T new_variable = Begin + 5;

 return (*new_variable);
}

because the compiler will not understand what T * means. The solution I was thinking about is to take what I am trying to return and make it the third argument:

template <class T> 
void func(T Begin, T End, T* new_variable)

 new_variable = Begin + 5;

 return (*new_variable);
}

Will this work? Even so, is there any other way to do what I'm trying to do? (Sorry if I was not clear enough.)

+5
2

( , ), :

template<typename RandomAccessIterator>
typename std::iterator_traits<RandomAccessIterator>::value_type 
func(RandomAccessIterator a, RandomAccessIterator b) {
    typedef typename std::iterator_traits<RandomAccessIterator>::value_type 
      value_type;

    // use value_type now, when you want to save some temporary
    // value into a local variable, for instance
    value_type t = value_type();
    for(; a != b; ++a) t += *a;
    return t;
}

, :

int main() {
  int d[3] = { 1, 2, 3 };
  assert(func(d, d + 3) == 6);
}
+10

, , , , . T - , ( ) T * ( , , ). T * - : , , , .

" " ++ (, decltype , decltype(*T())). T - : , .

+3

All Articles