std :: initializer_list<>和参考参数 [英] std::initializer_list<> and a Reference Parameter

查看:113
本文介绍了std :: initializer_list<>和参考参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用初始化列表,我想知道他们是否工作类似于其他stl容器。我的意思是他们复制值?我想做的是一个简单的min()函数像这样:

  template< class 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)
}
return * Smallest;但是当我调用函数时,我从GCC得到这个:



 错误:'const'限定符不能应用于'int&'

我一直在玩这个,似乎initializer_lists可能不会做我想要的;我想要的函数除了非POD参数,以及。

解决方案

当我尝试时,我会收到这些错误。但是,当我摆脱了对参考文献的无谓使用时,一切正常



std :: initializer_list 存储,而不是引用。你应该用一个 const std :: initializer_list< T> & ,而不是 const std :: initializer_list< T&> &


我所要做的就是写一个函数,通过引用,并返回对其中最大的引用。
[...]
这是否可能与initializer_lists?


否。 std :: initializer_list ,而不是引用。但我没有看到任何理由,你不能采取的价值,而不是通过参考的项目。或者,更重要的是,为什么不使用 std :: 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;
}

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?

这篇关于std :: initializer_list&lt;&gt;和参考参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆