search

Home  >  Q&A  >  body text

c++ - 接受右值引用参数的模板函数

#include <iostream>
#include <type_traits>
template<typename T>void g(T&& val);
int main() 
{
    int i = 0;
    const int ci = i;
    g(i*ci);//请问这里模板实例化的T是int还是int&&?我认为是int,但很多地方说是int&&,感觉不可思议
}
PHP中文网PHP中文网2803 days ago797

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 13:15:30

    If I remember correctly, T is int and val is int&&. You can read the first chapter of effective modern c++

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:15:30


    Write a program to verify it

    Sorry, I just wrote it wrong. The following is the correct verification scheme.


    The output is 10 and 999
    I just want to output val in g(), the value is 10
    Then I modify the val in g(), and then return When main outputs 999
    , it means that the parameters here are passed by reference, not by value.
    In other words, the message is T&

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 13:15:30

    The answer is: non-const rvalue reference.
    This problem is about understanding the left and right values.

    reply
    0
  • Cancelreply