0

我正在尝试使用引用包装器的向量运行一个示例,但在向量变量声明时遇到编译错误。这是代码:

#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 Tstd::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 构建)

4

1 回答 1

5

您正在初始化一个非const Basewithconst包装器:

vector<reference_wrapper<Base>> X{cref(x1), cref(x2)};

改用const Base

vector<reference_wrapper<const Base>> X{cref(x1), cref(x2)};
于 2019-09-02T14:27:57.047 回答