Search code examples
c++c++17variantstd-variant

How to simplify std::variant class types


I am sure there is a an easy way to do this but couldn't find anything in SO. Couldn't find much info in en.cppreference.com either.

Is there a way to simplify the std::variant</*class types*/> so that we can declare functions and classes that could take the same std::variant as an argument.

Consider this example:

I have a vector which acts as a container for the following std::variant;

std::vector<std::variant<Car, Space, Human>> EntityContainer;

if I want to pass this vector to a function as an argument, I have to do add the following parameter declaration.

void Function(std::vector <std::variant<Car, Space, Human>>& container);

I could perhaps use macros for this example but this doesn't really solve the problem.

Is there a better solution to this rather than listing same class types in std::variant over and over again everywhere around the project?

code live

#include <iostream>
#include <vector>
#include <variant>


class Human
{
public:
  void Talk(){ std::cout << "whass up\n"; }
};
class Car
{
public:
  void RunEngine() { std::cout << "Vroom\n"; }
};
class Space
{
public:
  void Expand() { std::cout << "Expand slowly\n"; }
};

struct VisitPackage
{
  void operator()(Human& obj) { obj.Talk();}
  void operator()(Car& obj) { obj.RunEngine();}
  void operator()(Space& obj) { obj.Expand();}
};  

void Function(std::vector <std::variant<Car, Space, Human>>& container)
{
  for (auto& entity : container)
  {
    std::visit(VisitPackage(), entity);
  }
}
int main()
{
  std::vector<std::variant<Car, Space, Human>> EntityContainer;
  EntityContainer.emplace_back(Car());
  EntityContainer.emplace_back(Human());
  EntityContainer.emplace_back(Space());
  Function(EntityContainer);

  return 0;
}

Solution

  • You're looking to define aliases. This can be done with using or typedef. using is more familiar to C++ programmers because of its syntax, typedef is C-compatible.

    typedef std::variant<int, double, float> arithmetic;
    using arithmetic = std::variant<int, double, float>;
    //Both are equivalent
    
    std::vector<arithmetic> entityContainer;
    void function(std::vector<arithmetic> const& vector) {
        /*...*/
    }