c++ - boost 变体 : Is there magic in the binding order?

标签 c++ boost boost-variant

我一直在阅读我能找到的关于 Boost Variant 的所有内容. (我很头疼。)有些人对分配字符串文字被保存为 bool 值感到惊讶。如果我在 bool 之前(之后?)列出了 char*,字符串文字会被保存为 char* 字符串吗? v1v2 之间的顺序在这里重要吗?

boost::variant<char*, bool> v1 = "hello";
boost::variant<bool, char*> v2 = "hello";

对于整数,我应该简单地绑定(bind)所有整数的最大整数还是应该单独绑定(bind) int8_tint64_t?如果我将它们全部绑定(bind),然后输入一个适合它们中的任何一个,它是否会保存为第一个(最后一个?)?

floatdouble 怎么样?

最佳答案

没有魔法。

只有记录在案的构造函数行为。

template<typename T> variant(T & operand);

Requires: T must be unambiguously convertible to one of the bounded types (i.e., T1, T2, etc.).

Postconditions: Content of *this is the best conversion of operand to one of the bounded types, as determined by standard overload resolution rules.

Throws: May fail with any exceptions arising from the conversion of operand to one of the bounded types.

因为这两种情况都涉及隐式转换,所以可能会构造出意想不到的元素类型。

看下面的例子

Live On Coliru

#include <boost/variant.hpp>

int main() {
    {
        boost::variant<bool, std::string> v;
        v = "hello"; // is char const(&)[6], converts to bool

        assert(0 == v.which());

        v = static_cast<char const*>("hello");
        assert(0 == v.which());
    }

    // compare to
    {
        boost::variant<bool, char const*> v;
        v = "hello"; // is char const(&)[6]

        assert(1 == v.which()); // now selects the direct match

        v = static_cast<char const*>("hello");
        assert(1 == v.which());
    }
}

关于c++ - boost 变体 : Is there magic in the binding order?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28093197/

相关文章:

c++ - 查询 std::binary_search()

c++ - 如何以正确的方式解方程并保存?

c++ - (shared_ptr+weak_ptr)兼容原始指针的设计

c++ - 为什么 boost::qi 规则的属性必须用括号声明?

c++ - 如何编写返回类型由运行时确定的函数(根据参数的值?)

c++ - 歧义消解

c++ - 我如何调用 dataChanged

c++ - 带有 boost 变体的递归 using 声明

c++ - 为什么 boost::spirit::qi::parse() 没有设置这个 boost::variant 的值?

c++ - boost::recursive_wrapper 和 std::unique_ptr