【问题标题】:Are implicit conversions allowed with std::tie?std::tie 是否允许隐式转换?
【发布时间】:2017-03-08 05:37:24
【问题描述】:

在 c++11 中,是否允许使用 std::tie 进行隐式转换?

以下代码可以编译并运行,但我不确定幕后究竟发生了什么,或者这是否安全。

std::tuple<float,float> foo() { return std::make_tuple(0,0); }

double a, b;
std::tie(a,b) = foo(); // a and b are doubles but foo() returns floats

【问题讨论】:

    标签: c++ c++11 tuples stdtuple


    【解决方案1】:

    使用元组的移动赋值运算符的模板版本会发生什么

    template< class... UTypes >
    tuple& operator=(tuple<UTypes...>&& other );
    

    它使用自己的移动分配语义一一移动分配单个元组成员。如果相应的成员是隐式可转换的 - 它们会被隐式转换。

    这基本上是 std::pair 中类似功能的自然扩展,我们已经享受了很长时间了。

    【讨论】:

    • 也许提一下隐式转换发生在operator= 的主体内是个好主意,因为在推导UTypes... 的过程中会忽略隐式转换。
    猜你喜欢
    • 2022-01-09
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    相关资源
    最近更新 更多