我正在尝试使用引用包装器的向量运行一个示例,但在向量变量声明时遇到编译错误。这是代码:
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
struct Base
{
virtual void print() = 0;
};
struct X1: public Base
{
void print() override
{
cout << "X1\n";
}
};
struct X2: public Base
{
void print() override
{
cout << "X2\n";
}
};
int main()
{
X1 x1;
X2 x2;
vector<reference_wrapper<Base>> X{cref(x1), cref(x2)};
}
std::initializer_list
带有存在的向量构造函数。传递的值的类型必须是const T
,std::cref
返回,为什么会报错:
/home/u1/sandbox/c++/trash/untitled/main.cpp:33: error: no matching function for call to ‘std::vector<std::reference_wrapper<Base> >::vector(<brace-enclosed initializer list>)’
vector<reference_wrapper<Base>> X{cref(x1), cref(x2)};
^
? (如果重要,使用 gcc -std=c++17 构建)