Home > Software design >  using the current type in typedef in cpp
using the current type in typedef in cpp

Time:01-01

I need a data type which will hold either a string or a vector of the current data type. Here is a typedef I've written for that:

typedef std::variant<std::vector<value>, std::string> value;

Apparently this isn't valid, as value is an undeclared identifier when executing this line. So I tried first declaring value as another type and then using it in the same type:

typedef int value;
typedef std::variant<std::vector<value>, std::string> value;

this didn't work either, because the types are different.

So knowing this, what is the proper way of using the current type in a typedef?

CodePudding user response:

I think this is what you're asking for:

struct Type
{
    using Value = std::variant<std::vector<Type>, std::string>;
    Value v;
};

CodePudding user response:

Instead of this, I created a class with a getter and a setter method:

class value {
  std::vector<value> children;
  std::string val;

 public:
  int index;
  value(
      std::variant<std::vector<value>, std::string> v) {
    this->set_value(v);
  }

  void set_value(
      std::variant<std::vector<value>, std::string> v) {
    if (v.index() == 0) {
      children = std::get<std::vector<value>>(v);
      index = 0;
    } else {
      this->val = std::get<std::string>(v);
      index = 1;
    }
  }

  std::variant<std::vector<value>, std::string> get_value() {
    if (index == 0) {
      return children;
    } else {
      return this->val;
    }
  }
};
  • Related