std :: initializer_list& lt;& gt;和参考参数 [英] std::initializer_list<> and a Reference Parameter
问题描述
我是使用初始化列表的新手,我想知道它们是否类似于其他stl容器.我的意思是说他们复制值吗?我正在尝试做的是一个简单的min()函数,如下所示:
I'm new to using initializer lists and I'm wondering if they work similar to other stl containers. By that I mean do they copy values? What I'm trying to do is a simple min() function like this:
template <class T> T& minArgs(const std::initializer_list<T&>& Arguments)
{
const T* Smallest = Arguments.begin();
for (const T* I = begin(Arguments); I != end(Arguments); ++I)
{
if (*I < *Smallest) Smallest = I;
}
return *Smallest;
}
但是,当我调用该函数时,我是从GCC获得的:
However when I call the function I get this from GCC:
error: 'const' qualifiers cannot be applied to 'int&'
我一直在玩这个游戏,似乎initializer_lists可能无法满足我的要求;我希望该函数也能排除非POD参数.va_list会是更好的选择吗?
I've been playing around with this and it seems initializer_lists may not do what I want; I want the function to except non-POD arguments as well. Would a va_list be a better alternative?
谢谢!
推荐答案
尝试时,出现这些错误.但是,当我摆脱了对引用的毫无意义的使用时,所有的方法都可以使用.
When I try it, I get these errors. Yet, when I get rid of your pointless use of references, it all works.
std :: initializer_list
存储值,而不是引用.您应该使用 const std :: initializer_list< T>&
,而不是 const std :: initializer_list< T&>&
.
std::initializer_list
stores values, not references. You should be taking a const std::initializer_list<T> &
, not a const std::initializer_list<T&> &
.
我要做的就是编写一个函数,该函数通过引用接受任意数量的参数,并返回对其中最大参数的引用.[...]使用initializer_lists是否可以?
All I'm trying to do is write a function that takes any number of arguments, by reference, and returns a reference to the largest of them. [...] Is this possible with initializer_lists?
不. std :: initializer_list
用于值,而不是引用.但是我看不出为什么您不能按价值而不是按引用来接受这些项目.或者,更重要的是,为什么不只使用 std :: min
,它可以包含一个初始化列表?
No. std::initializer_list
is for values, not references. But I see no reason why you couldn't take the items by value instead of by reference. Or, more to the point, why don't you just use std::min
, which can take an initializer list?
这篇关于std :: initializer_list& lt;& gt;和参考参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!