C++17 std::variant<class... Types>
有一个转换构造函数
template< class T >
constexpr variant(T&& t) noexcept(/* see below */);
(http://en.cppreference.com/w/cpp/utility/variant/variant 中的第 4 个)。它的描述是一堵相当坚不可摧的文字墙。这是否意味着变体有一堆
template< class T_i > constexpr variant(T_i&& t) noexcept;
构造器,类型中的每个 T_i 一个?
最佳答案
让我们分解一下描述:
Constructs a variant holding the alternative type
T<sub>j</sub>
that would be selected by overload resolution for the expressionF(std::forward<T>(t))
if there was an overload of imaginary functionF(T<sub>i</sub>)
for everyT<sub>i</sub>
fromTypes...
in scope at the same time.
假设我们在文档中有示例:
variant<string, bool> x("abc"); // OK, but chooses bool
-
Types...
是<string, bool>
if there was an overload of imaginary function
F(T<sub>i</sub>)
for everyT<sub>i</sub>
fromTypes...
int F(string) { return 0; }
int F(bool) { return 1; }
selected by overload resolution for the expression
F(std::forward<T>(t))
template <typename T>
void select(T&& t)
{
std::cout << F(std::forward<T>(t)) << '\n';
}
int main()
{
select("abc"); // prints `1`
}
Constructs a variant holding the alternative type
T<sub>j</sub>
[...]
选择的替代类型 T<sub>j</sub>
因此是bool
.
关于c++ - std::variant 转换构造函数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49109725/