用reference_wrappers初始化向量

时间:2019-09-02 14:21:24

标签: c++ vector initializer-list reference-wrapper

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

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

1 个答案:

答案 0 :(得分:4)

您正在使用const包装器初始化非Base const

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

改为使用const Base

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