[英]Why I can't use a reference type inside a `std::initializer_list`
when I try to use an initializer list for a member that contains references, I get the following error: 当我尝试对包含引用的成员使用初始化列表时,出现以下错误:
no matching function for call to ‘std::vector<const Exp&>::vector(<brace-enclosed initializer list>)’
I have read several related posts, but first, they seem to get a different error; 我已经阅读了几篇相关的文章,但首先,它们似乎出现了不同的错误; second, they qualify the use of references "as pointless".
第二,他们认为引用的使用“毫无意义”。
Without getting into philosophical discussions, indeed I would appreciate knowing if it is possible to make the below example work: 在不进行哲学讨论的情况下,确实希望了解以下示例是否可行:
#include <vector>
class Exp {
};
class Integer : public Exp {
public:
const int value;
Integer(const int val) : value(val) { }
};
int main() {
const auto a1 = Integer(1);
const auto a2 = Integer(2);
const std::vector<const Exp&> va{a1,a2};
}
Could it be a missing constructor for the vector
class? vector
类可能缺少构造函数吗? Thanks a lot! 非常感谢!
gcc (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413
[Edited to remove spurious example] [编辑以删除虚假示例]
Although this is not explicitly stated in the standard, attempting to use standard library containers to store non-object types should be regarded as undefined behaviour. 尽管标准中没有明确说明,但尝试使用标准库容器存储非对象类型应视为未定义的行为。 See [container.requirements.general],
参见[container.requirements.general],
p1: "Containers are objects that store other objects..." p1:“容器是存储其他对象的对象...”
p4: "... X
denotes a container class containing objects of type T
..." p4:“ ...
X
表示包含T
类型对象的容器类...”
and so on. 等等。
Thanks to everybody!!! 谢谢大家!!! I've settled on this solution for now:
我现在已经确定了这个解决方案:
std::array<const std::reference_wrapper<const Exp>, 2> ae{a1,a2};
I need to investigate more but I think that will do what I want for now. 我需要进行更多调查,但我认为这将满足我目前的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.