I am trying to run an example with vector of reference wrappers, but run into compilation error at the vector variable declaration. Here is the code:
#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)};
}
The vector constructor with std::initializer_list
exists. The type of the passed values must be const T
, which std::cref
returns, so why does it complain:
/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)};
^
? (building with gcc -std=c++17 if it matters)