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;
}
However when I call the function I get this from GCC:
error: 'const' qualifiers cannot be applied to 'int&'
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?
Thanks!
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
stores values, not references. You should be taking a const std::initializer_list<T> &
, not a const std::initializer_list<T&> &
.
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?
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?
来源:https://stackoverflow.com/questions/13243578/stdinitializer-list-and-a-reference-parameter