我一直在阅读我能找到的关于 Boost Variant 的所有内容. (我很头疼。)有些人对分配字符串文字被保存为 bool 值感到惊讶。如果我在 bool
之前(之后?)列出了 char*
,字符串文字会被保存为 char*
字符串吗? v1
和 v2
之间的顺序在这里重要吗?
boost::variant<char*, bool> v1 = "hello";
boost::variant<bool, char*> v2 = "hello";
对于整数,我应该简单地绑定(bind)所有整数的最大整数还是应该单独绑定(bind) int8_t
到 int64_t
?如果我将它们全部绑定(bind),然后输入一个适合它们中的任何一个,它是否会保存为第一个(最后一个?)?
float
和 double
怎么样?
最佳答案
没有魔法。
只有记录在案的构造函数行为。
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.
因为这两种情况都涉及隐式转换,所以可能会构造出意想不到的元素类型。
看下面的例子
#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/