Why ={} initialization doesn't work for tuple?

前端 未结 2 1516
醉话见心
醉话见心 2020-12-14 16:11

To me a pair is just special case of a tuple, but following surprises me:

pair p1(1, 2);   // ok
tuple

        
相关标签:
2条回答
  • 2020-12-14 16:24

    In addition to Praetorian's correct answer (which I've upvoted), I wanted to add a little more information...

    Post-C++14, the standard has been changed to allow:

    tuple<int, int> t2={1, 2}; 
    

    to compile and have the expected semantics. The proposal that does this is N4387. This will also allow constructs such as:

    tuple<int, int>
    foo()
    {
        return {1, 2};
    }
    

    It only allows it if all T in the tuple are implicitly contructible from all arguments.

    As a non-conforming extension, libc++ already implements this behavior.

    0 讨论(0)
  • 2020-12-14 16:36

    The tuple constructor you're trying to call is explicit, so copy-list-initialization will fail. The corresponding pair constructor is not explicit.

    Change your code to

    tuple<int, int> t2{1, 2};
    

    and it'll compile.

    0 讨论(0)
提交回复
热议问题