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

标签 c++ c++17

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/

相关文章:

c++ - 使用指令和部分特化

c++ - 我可以从 C++17 折叠表达式中解析出单个函数吗

c++ - 使用 C++17,如何创建类型到值的编译时映射?

c++ - 如何获得支持枚举的类型

c++ - 在父对象上调用成员函数?

c++ - 类型转换会导致问题吗?

c++ - Windows 上的 C++17 是否与 ubuntu 上的 C++17 一致?

c++ - 执行策略之间的差异以及何时使用它们

C++ 相同命名空间问题

python - 无法从 python C++ 包装器访问析构函数