英文:
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,以便更容易阅读返回类型。是否有办法在声明中实现这一点?
英文:
For this template declaration:
template <class Iterator>
typename std::iterator_traits<Iterator>::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?
答案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 <typename Iterator>
using iterator_value_type_t = typename std::iterator_traits<Iterator>::value_type;
and then you can use that with your function like
template <class Iterator>
iterator_value_type_t<Iterator> 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 <class Iterator,
class ReturnType = typename std::iterator_traits<Iterator>::value_type>
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<Iterator>::value_type
:
template <class It>
using itval= std::iterator_traits<It>::value_type;
//And use it:template <class Iterator>
itval<Iterator> Mean(Iterator begin, Iterator end);
In general for templates you should use the using
keyword. Typedef can't support templates.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论