我有一个整数数组来检索 std::variant 中的内容。但是编译失败,报错No matching function to call 'get'
.您能否解释原因,并提出实现相同目的的可行解决方案?
using my_type = std::variant<int, float, bool>;
constexpr int[] expected_types = {2,2,2,2};
bool validate(std::vector<my_type> input) {
bool rst;
if (input.size() != 4) {
return false;
}
for (int i = 0; i < 4; i++) {
rst = rst || std::get<my_type[i]>(input[i]);
}
return rst;
}
这里有更多的上下文。 A、B、C类都实现了接口(interface)bool foo(std::vector<my_type> input)
.但是A类的输入是{int, int, bool}的格式,B类的输入是{int, int, float}的格式,C类的输入是{bool,bool}的格式。每个类中的 expected_types 在输入 vector 中保存自己的类型。然后 std::get
非常感谢!
最佳答案
如果我理解你的validate
正常运行,它应该验证 vector<variant<int, float, bool>>
...
A
具有正确的长度, B
或 C
.variant
variant
指示的类型A::expected_types[]
中的索引, B::expected_types[]
或 C::expected_types[]
.然后它可以采用正在测试的类型 vector
for ( A
, B
或 C
) 作为模板参数并使用 variant::index()
检查个人的类型variant
s 持有 vector
.
将它与折叠结合 &&
(因为你希望所有的都是 true
)你会得到:
template<class T>
bool validate(const std::vector<my_type>& input) {
if (input.size() != std::size(T::expected_types)) return false;
return [&]<std::size_t... Is>(std::index_sequence<Is...>) {
// fold over && :
return (... && (input[Is].index() == T::expected_types[Is]));
}(std::make_index_sequence<std::size(T::expected_types)>());
}
如果你真的想要std::get
expected_types
来自 vector
并使用逻辑 OR
, 这可以用类似的方式完成,但折叠 ||
:
template <class T>
bool get_bool(const std::vector<my_type>& input) {
if (not validate<T>(input)) return false; // use the validation function above
return [&]<std::size_t... Is>(std::index_sequence<Is...>) {
// fold over ||
return (... || (std::get<T::expected_types[Is]>(input[Is])));
}(std::make_index_sequence<std::size(T::expected_types)>());
}
Demo
关于c++ - std::variant 使用整数数组中的元素作为 std::variant 中的目标类型从 std::variant 获取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75281033/
相关文章:
c++ - 是不是 vector.at(vector.size()-1) 比 vector.back
python - 查找给定范围内的数字,使给定列表中任何元素的数字的 gcd 始终为 1
pdf - PDF 的 BitsPerComponent 如何转换为图像的每像素位数?
sql-server-2005 - 强制 SQL Server 列为特定值
fortran - Fortran 能否在逻辑运算中强制遵守参数顺序?
vbscript - 当我的 InstallShield 安装程序尝试运行我的 VBS 自定义操作时
sql-server - 从现有数据库生成 SQL DDL 和内容的工具