【问题标题】:boost::variant with bool and stringboost::variant 与 bool 和 string
【发布时间】:2020-12-12 10:52:01
【问题描述】:

我在使用 boost::variant 时遇到问题(使用 boost 1.67.0)。

当我的模板参数列表同时包含 boolstd::string 时,任何应该被视为字符串的变体对象似乎都隐式绑定到 bool。例如:

using Varval = boost::variant<bool, std::string>;

void main()
{
    std::vector<Varval> vect{ true, false, "Hello_World" };

    std::cout << "[ ";
    for (const auto &v : vect)
        std::cout << v << "  ";
    std::cout << "]\n";
}

输出:

[1 0 1]

而如果我只更改第一个模板参数,从 boolint,它工作正常:

using Varval = boost::variant<int, std::string>;

void main()
{
    std::vector<Varval> vect{ true, false, "Hello_World" };

    std::cout << "[ ";
    for (const auto &v : vect)
        std::cout << v << "  ";
    std::cout << "]\n";
}

正确输出:

[1 0 Hello_World]

有什么想法吗?

【问题讨论】:

  • “Hello_World”不是string。它是const char*
  • “Hello_World”不是const char*,而是char[12]

标签: c++ boost


【解决方案1】:

boost::variant 对每个声明的类型都有一个构造函数重载。在您的第一个示例中,bool 将有一个重载,std::string 将有一个重载。您现在使用 char[n] 调用构造函数,它可以隐式转换为它们两者。所以没有完美的匹配,只有两个候选人。但编译器不会告诉您调用不明确,而是选择bool 重载作为更好的匹配。

为什么?这已经得到了完美的回答in this question

在您使用intstd::string 的第二个示例中,您将bools 和char[n] 传递给构造函数。 bool 可以隐式转换为int,但不能转换为std::stringchar[n] 可以隐式转换为std::string,但不能转换为int。因此调用相应的构造函数,因为每个构造函数只有一个候选者。

【讨论】:

  • 这是有道理的。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 2013-08-02
  • 2017-03-05
相关资源
最近更新 更多