Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

c++ - Can't bind lvalue to rvalue in member function but ok in global function

While looking at the reference pages for std::forward I came across something odd. The example is passing an lvalue as an rvalue reference.. but to a global function... and it compiles and runs. I tried the same thing as a member function and it fails to compile. What gives? I would expect both calls to fail without the use of std::move or std::forward<T>.

#include <iostream>

template <typename T>
void globalDoSomething(T &&data) {
    std::cout << "We're doing it!!" << std::endl;
}

template <typename T>
class A {
public:
    void doSomething(T &&data);
};

template <typename T>
void A<T>::doSomething(T &&data)
{
    std::cerr << "Ah, man. I won't compile." << std::endl;
}

template class A<int>;

int main()
{

    int b = 0;
    globalDoSomething(b);

    A<int> a;
    a.doSomething(b);

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's because the automatic template deduction for globalDoSomething infers T as int&.

If you explicitly instantiate the template function with globalDoSomething<int>(b); like you did for the member function of the template class, it will also fail to compile.

Conversely, if you instantiate the template class with A<int&> a;, it will successfully compile.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...