make_pair() in C++

前端 未结 2 998
庸人自扰
庸人自扰 2021-01-29 12:35

I was doing the problem 337 from leetcode. This is the code I implemented.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *              


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-29 12:53

    TL;DR: Don't specify template arguments of std::make_pair. Let the compiler deduce them.


    The meaning of template parameters of std::make_pair was changed in C++11.

    It used to be:

    template  /*...*/ make_pair( T1 t, T2 u );
    

    But now it is:

    template  /*...*/ make_pair(T1 &&t, T2 &&u);
    // `t` and `u` are forwarding references.
    

    The code was valid pre-C++11, but it no longer is.

    You could change the template arguments accordingly: make_pair(root, result), but there is no reason to specify them manually. The compiler can deduce them just fine.

    If you don't understand why the template arguments have to be references, read about forwarding references.


    Why ... the arguments in make_pair<>() become references?

    Probably your compiler displayed argument types as references to indicate that you're passing lvalues into make_pair.

提交回复
热议问题