在 cpp 中使用 typedef 中的当前类型
using the current type in typedef in cpp
我需要一个数据类型来保存当前数据类型的字符串或向量。这是我为此写的typedef
:
typedef std::variant<std::vector<value>, std::string> value;
显然这是无效的,因为 value
是执行此行时未声明的标识符。所以我首先尝试将 value
声明为另一种类型,然后在同一类型中使用它:
typedef int value;
typedef std::variant<std::vector<value>, std::string> value;
这也没有用,因为类型不同。
知道这些后,在 typedef
中使用当前类型的正确方法是什么?
我用 getter 和 setter 方法创建了一个 class,而不是这个:
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;
}
}
};
我想这就是你要的:
struct Type
{
using Value = std::variant<std::vector<Type>, std::string>;
Value v;
};
我需要一个数据类型来保存当前数据类型的字符串或向量。这是我为此写的typedef
:
typedef std::variant<std::vector<value>, std::string> value;
显然这是无效的,因为 value
是执行此行时未声明的标识符。所以我首先尝试将 value
声明为另一种类型,然后在同一类型中使用它:
typedef int value;
typedef std::variant<std::vector<value>, std::string> value;
这也没有用,因为类型不同。
知道这些后,在 typedef
中使用当前类型的正确方法是什么?
我用 getter 和 setter 方法创建了一个 class,而不是这个:
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;
}
}
};
我想这就是你要的:
struct Type
{
using Value = std::variant<std::vector<Type>, std::string>;
Value v;
};