gpt4 book ai didi

c++ - std::variant 转换构造函数行为

转载 作者:太空狗 更新时间:2023-10-29 20:34:20 27 4
gpt4 key购买 nike

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 expression F(std::forward<T>(t)) if there was an overload of imaginary function F(T<sub>i</sub>) for every T<sub>i</sub> from Types... 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 every T<sub>i</sub> from Types...

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`
}

live example on wandbox


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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com