boost :: variant将static_visitor应用于某些类型 [英] boost::variant apply static_visitor to certain types

查看:72
本文介绍了boost :: variant将static_visitor应用于某些类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下变体:

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

我想创建一个访问者,将 int float 类型转换为 bool 类型.

And I want to create a visitor to convert a int or float type to a bool type.


struct ConvertToBool : public boost::static_visitor<TypeVariant> {

    TypeVariant operator()(int a) const {
        return (bool)a;
    }

    TypeVariant operator()(float a) const {
        return (bool)a;
    }
};

但是这给了我错误消息:

However this is giving me the error message:

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

'TypeVariant ConvertToBool::operator ()(float) const': cannot convert argument 1 from 'T' to 'float'

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

What is the correct way of allowing a visitor to only apply to certain types?

推荐答案

只需包含丢失的重载即可:

Just include the missing overload:

在Coliru上直播

Live On 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";
    }
}

概括

在更一般的情况下,您可以提供全面的模板重载:

Generalize

In more general cases you can supply a catch-all template overload:

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

实际上,在您的琐碎情况下,反正是您所需要的:

In fact in your trivial case that's all you needed anyways:

在Coliru上直播

Live On 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

这篇关于boost :: variant将static_visitor应用于某些类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆