std::initializer_list<> and a Reference Parameter

谁说胖子不能爱 提交于 2019-12-22 08:39:19

问题


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!


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!