获取模板声明中迭代器的值类型的方法是?

huangapple go评论69阅读模式
英文:

How to get the value type of an iterator in a template declaration?

问题

以下是翻译好的部分:

对于这个模板声明:

template <class Iterator>
typename std::iterator_traits<Iterator>::value_type Mean(Iterator begin, Iterator end);

我想通过"using声明"或typedef来简化value_type的typename,以便更容易阅读返回类型。是否有办法在声明中实现这一点?

相关帖子:
1
2

英文:

For this template declaration:

template &lt;class Iterator&gt;
typename std::iterator_traits&lt;Iterator&gt;::value_type Mean(Iterator begin, Iterator end);

I would like to simplify the value_type typename with a "using declaration" or typedef. So that it is a easier to read the return type. Is there a way to do this in the declaration?

Related posts
1
2

答案1

得分: 2

你可以添加一个模板别名,例如

template <typename Iterator>
using iterator_value_type_t = typename std::iterator_traits<Iterator>::value_type;

然后你可以在函数中使用它,例如

template <class Iterator>
iterator_value_type_t<Iterator> Mean(Iterator begin, Iterator end);

如果你想允许指定自定义的返回类型,那么你可以将返回类型移到模板参数列表中,如下所示:

template <class Iterator, 
          class ReturnType = typename std::iterator_traits<Iterator>::value_type>
ReturnType Mean(Iterator begin, Iterator end);
英文:

You can add an template alias like

template &lt;typename Iterator&gt;
using iterator_value_type_t = typename std::iterator_traits&lt;Iterator&gt;::value_type;

and then you can use that with your function like

template &lt;class Iterator&gt;
iterator_value_type_t&lt;Iterator&gt; Mean(Iterator begin, Iterator end);

If you want to allow specifying a custom return type then you can move the return type into the template parameter list like

template &lt;class Iterator, 
          class ReturnType = typename std::iterator_traits&lt;Iterator&gt;::value_type&gt;
ReturnType Mean(Iterator begin, Iterator end);

答案2

得分: 0

你可以创建一个别名到 std::iterator_traits<Iterator>::value_type

template <class It>
using itval = typename std::iterator_traits<It>::value_type;

// 然后使用它:
template <class Iterator>
itval<Iterator> Mean(Iterator begin, Iterator end);

通常对于模板,你应该使用 using 关键字。typedef 不能支持模板。

英文:

You can create an alias to std::iterator_traits&lt;Iterator&gt;::value_type:

template &lt;class It&gt;
using itval= std::iterator_traits&lt;It&gt;::value_type;

//And use it:template &lt;class Iterator&gt;
itval&lt;Iterator&gt; Mean(Iterator begin, Iterator end);

In general for templates you should use the using keyword. Typedef can't support templates.

huangapple
  • 本文由 发表于 2023年2月9日 01:21:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75389471.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定