【问题标题】:boost::variant visitor chooses the wrong overloadboost::variant 访问者选择了错误的重载
【发布时间】:2013-03-26 11:39:46
【问题描述】:

为什么会打印出"A boolean!"?我意识到正在进行一些奇怪的转换,因为如果我明确地构造一个 std::string 我会得到正确的行为。但是为什么在下面的情况下重载解析会选择visitor::operator()(bool)呢?

#include <boost/variant.hpp>
#include <string>

typedef boost::variant<bool, std::string> type;

struct visitor : public boost::static_visitor<> {
    void operator()(bool b) const {
        std::cout << "A boolean!" << std::endl;
    }

    void operator()(const std::string& str) const {
        std::cout << "A string!" << std::endl;
    }
};

int main(int argc, char* argv[]) {
    type t = "I am a string";
    t.apply_visitor(visitor());

    return 0;
}

我正在运行 Visual Studio 2012(CTP 或不给出相同的结果)

【问题讨论】:

  • FTR apply_visitor 成员不是公共接口的一部分。您应该使用独立版本:apply_visitor(visitor(), t)
  • 谢谢@LucDanton。当我阅读文档时错过了这一点

标签: c++ boost boost-variant apply-visitor


【解决方案1】:

您正在使用(衰减到的类型)const char* 初始化 t。将指针转换为bool 是标准转换,而将const char* 转换为std::string 是用户定义的转换。标准转换优先。

【讨论】:

    猜你喜欢
    • 2011-04-06
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2014-04-25
    相关资源
    最近更新 更多