Parameter redirection in C ++

I have a class and a wrapper around it. For instance:

#include <iostream>
#include <string>

template<typename T>
class inner
{
public:
    void f(T& v) { std::cout<<"lvalue: "<<v<<std::endl;}
    void f(T&& v) { std::cout<<"rvalue: "<<v<<std::endl;}
};

template<typename T>
class wrapper
{
public:
    template<typename _T>
    void f(_T&& v) { i.f(std::forward<T>(v)); } //(1)

private:
    inner<T> i;
};

int main()
{
    wrapper<std::string> c;
    //inner<std::string> c;

    c.f("r");

    std::string s = "l";
    c.f(s);
}

In the case where cthere is inner, the conclusion is correct:

rvalue: r
lvalue: l

But when cthere is a wrapperconclusion is incorrect:

rvalue: r
rvalue: l

Why did the l-value become the r-value?

And what's the difference if the definition wrapper fin the line (1)would be:

    template<typename _T>
    void f(_T v) { i.f(std::forward<T>(v)); } //without &&
+4
source share
1 answer

Because you do:

template<typename _T>
void f(_T&& v) { i.f(std::forward<T>(v)); } //(1)
                                  ^
                                  T, not _T

You always use T, not a deduced type v. For clarity, you really do:

template <typename _T>
void f(_T&& v) {
    i.f(std::forward<std::string>(v));
}

And the type std::forward<std::string>(v)is equal string&&.

For your second question:

template<typename _T>
void f(_T v) { i.f(std::forward<T>(v)); } //without &&

_T , std::forward<T>(v) std::move(v) - rvalue.

+3

Source: https://habr.com/ru/post/1584326/


All Articles