boost::variant将static_visitor应用于某些类型



我有以下变体:

typedef boost::variant<int, float, bool> TypeVariant;

我想创建一个访问者,将intfloat类型转换为bool类型。


struct ConvertToBool : public boost::static_visitor<TypeVariant> {
TypeVariant operator()(int a) const {
return (bool)a;
}
TypeVariant operator()(float a) const {
return (bool)a;
}
};

然而,这给了我错误信息:

"TypeVariant ConvertToBool::operator(((float(const":无法将参数1从"T"转换为"float">

允许访问者只应用于某些类型的正确方法是什么?

只包括丢失的过载:

在Coliru上直播

#include <boost/variant.hpp>
#include <iostream>
using TypeVariant = boost::variant<int, float, bool>;
struct ConvertToBool {
using result_type = TypeVariant;
TypeVariant operator()(TypeVariant const& v) const {
return boost::apply_visitor(*this, v);
}
TypeVariant operator()(int   a) const { return a != 0; }
TypeVariant operator()(float a) const { return a != 0; }
TypeVariant operator()(bool  a) const { return a; }
} static constexpr to_bool{};
int main() {
using V = TypeVariant;

for (V v : {V{}, {42}, {3.14f}, {true}}) {
std::cout << v << " -> " << std::boolalpha << to_bool(v) << "n";
}
}

泛化

在更常见的情况下,您可以提供一个包罗万象的模板重载:

template <typename T> TypeVariant operator()(T const& a) const {
return static_cast<bool>(a);
}

事实上,在你琐碎的情况下,这就是你所需要的:

在Coliru上直播

#include <boost/variant.hpp>
#include <iostream>
using TypeVariant = boost::variant<int, float, bool>;
struct ConvertToBool {
using result_type = TypeVariant;
TypeVariant operator()(TypeVariant const& v) const {
return boost::apply_visitor(*this, v);
}
template <typename T> TypeVariant operator()(T const& a) const {
return static_cast<bool>(a);
}
} static constexpr to_bool{};
int main() {
using V = TypeVariant;
for (V v : { V{}, { 42 }, { 3.14f }, { true } }) {
std::cout << v << " -> " << std::boolalpha << to_bool(v) << "n";
}
}

静态打印

0 -> false
42 -> true
3.14 -> true
true -> true

最新更新