微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我不能将std :: from_chars的结果分配给std :: tie?

如何解决为什么我不能将std :: from_chars的结果分配给std :: tie?

我当时在想,我可以将auto [x,y]分配给由现有变量组成的std::tie,但是由于某种原因,它不起作用。谁能告诉我为什么?恐怕我不理解编译器消息。在我看来,它试图将整数分配给元组(???)

#include <charconv>
#include <tuple>
int main()
{
    auto s = "123";
    unsigned int val;
    auto [p,err] = std::from_chars(s,s+3,val);       // this compiles
    std::tie(p,err) = std::from_chars(s,val);     // this doesn't compile
}
> c++ -std=c++17 foo.cpp
foo.cpp: In function ‘int main()’:
foo.cpp:8:50: error: no match for ‘operator=’ (operand types are ‘std::tuple<const char*&,std::errc&>’ and ‘std::__detail::__integer_from_chars_result_type<unsigned int>’ {aka ‘std::from_chars_result’})
     std::tie(p,val);     // this doesn't compile
                                                  ^
In file included from foo.cpp:2:
/usr/include/c++/8/tuple:1209:7: note: candidate: ‘std::tuple<_T1,_T2>& std::tuple<_T1,_T2>::operator=(const std::tuple<_T1,_T2>&) [with _T1 = const char*&; _T2 = std::errc&]’
       operator=(const tuple& __in)
       ^~~~~~~~
/usr/include/c++/8/tuple:1209:7: note:   no kNown conversion for argument 1 from ‘std::__detail::__integer_from_chars_result_type<unsigned int>’ {aka ‘std::from_chars_result’} to ‘const std::tuple<const char*&,std::errc&>&’
/usr/include/c++/8/tuple:1216:7: note: candidate: ‘std::tuple<_T1,_T2>::operator=(std::tuple<_T1,_T2>&&) [with _T1 = const char*&; _T2 = std::errc&]’
       operator=(tuple&& __in)

这个示例可以完美地编译:

int a,b,c;
std::tie(a,c) = std::make_tuple(2,3,4);

解决方法

这是两种不同的构造。

auto [p,err] = std::from_chars(s,s+3,val);       // this compiles

这是结构化绑定,可以将任何结构元素(数组,结构,元组等)绑定到单个标识符。参见:Structured Binding

另一方面,此代码:

std::tie(p,err) = std::from_chars(s,val);     // this doesn't compile

它正在尝试为无法进行隐式转换的元组分配结构。只能将其他元组和成对对象分配给元组。参见:Tuple

尽管您可以覆盖赋值运算符以将结构转换为元组,然后您的语句也可以正常工作。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。