-1

I try to store a reference to a std::vector consisting of std::variant. I can create a const std::variant<T>& to a element of a vector, but I struggle to store the reference to the whole vector. I guess that the answer is related to this post c++ variant class member stored by reference but I am not able to apply it to my situation.

#include <vector>
#include <variant>

using MType = std::variant<int, double>;
int main()
{
      std::vector<int> intVec{ 1,2,3,4 };
      std::vector<double> dlVec{ 1.1,2.2,3.3,4.4 };

      const MType& refVar = intVec[0];
      // const std::vector<MType>& refVec = intVec; // compiler error: not suitable construction 
}
moi
  • 467
  • 4
  • 19
StephanH
  • 463
  • 4
  • 12
  • 1
    Having a reference to something implies having that thing. You don't have any `std::vector` in your code, therefore you cannot have any `std::vector&`. – Nelfeal Jan 02 '19 at 16:56

2 Answers2

4

You can assign an int to a variant<int, double>, and you can assign a double to a variant<int, double>, but neither is a variant<int, double> and a vector<variant<int, double>> is not a vector<int> or a vector<double>.

You simply can't do this.

Is it possible that you meant variant<vector<int>, vector<double>>?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

I can create a const std::variant& to a element of a vector,

With

const MType& refVar = intVec[0];

you don't create reference to element of intVec but create a temporary (with life time extension).

So it is basically:

const std::variant<int, double> var = intVec[0];

but i struggle to store the reference to the whole vector

In the same way with std::vector, you might create a std::vector<std::variant<int, double>>:

std::vector<std::variant<int, double>> varVec(intVec.begin(), intVec.end());
Jarod42
  • 203,559
  • 14
  • 181
  • 302