简体   繁体   English

在C ++模板函数中,我可以返回一个解除引用的参数类型吗?

[英]In a C++ template function can I return a dereferenced argument type?

What I mean is the following. 我的意思是以下内容。 I want a template function that takes two vector iterators (or two pointers to array of double) and returns a double that is somehow related to the vector iterators or array pointers that I pass. 我想要一个模板函数,它接受两个向量迭代器(或两个指向double数组的指针)并返回一个double,它以某种方式与我传递的向量迭代器或数组指针相关。 However, I want this to work for double or int, or any arithmetic type. 但是,我希望这适用于double或int,或任何算术类型。

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 won't understand what T* means. 因为编译器不会理解T *的含义。 A solution I thought of is to take what I'm trying to return and make it a 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 if so, is there another way of doing what I'm trying to do? 即便如此,还有另一种方法可以做我想做的事情吗? (Sorry if I haven't been clear enough.) (对不起,如果我还不够清楚的话。)

If you want to return a double (ie the type that you would get when dereferencing), you can use the iterator traits: 如果要返回double(即取消引用时将获得的类型),可以使用迭代器特征:

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;
}

These work for all iterators, including pointers: 这些适用于所有迭代器,包括指针:

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

Well, your code seems to contradict what you described in the text. 好吧,你的代码似乎与你在文中描述的内容相矛盾。 If T is the iterator type, then the result of the iterator dereference (as you said in the text) will not have type T * (as you seem to believe in the code). 如果T是迭代器类型,则迭代器解除引用的结果(正如您在文中所述)将具有类型T * (因为您似乎相信代码)。 T * is a completely opposite thing: it is something you'd get if you took the address of your iterator, not dereferenced it. T *是一个完全相反的东西:如果你获取迭代器的地址 ,而不是取消引用它,它就是你得到的东西。

In fact, there's no way to express the "dereferenced type" using C++ core language features (maybe decltype will do it in the future, as in decltype(*T()) ). 实际上,没有办法使用C ++核心语言特性表达“解除引用类型”(也许decltype将来会这样做,如在decltype(*T()) )中。 The only way to describe the result of dereference of type T is to use a library-based solution: iterator traits, as Johannes explained in his answer. 描述类型T的解引用结果的唯一方法是使用基于库的解决方案:迭代器特征,正如Johannes在他的回答中所解释的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM