Pergunta

Ok so I'm playing a little bit with move c'tors and I've come to a silly question, Why can't std::forward deduce it's own parameters at some cases(Let's say not at inheritence), Consider the following code:

#include <iostream>
using namespace std;
struct Moveable {
    Moveable(){}
    Moveable(Moveable const& other) { cout << "Moveable::Copying" << endl;}
    Moveable(Moveable&& other) { cout << "Moveable::Moving" << endl;}
};
struct A {
    virtual ~A() {}
    A(){}
    A(A const& other) : m(other.m) { cout << "A::Copying" << endl;}
    A(A&& other) : m(forward<Moveable>(other.m))   { cout << "A::Moving" << endl;} // <--- why can't the compiler deduce that forward is templated over Moveable, just by the fact that he received moveable as the input parameter?
    Moveable m;
};

struct B : public A {
    B(B const& other) : A(other) { cout << "B::Copying" << endl;}
    B(B&& other) : A(forward<A>(other))    { cout << "B::Moving" << endl;} //<--- obvious why I need to forward, because I am to tell him to forward it as a parent class
    B(){}
};
int _tmain(int argc, _TCHAR* argv[])
{
    B b;
    cout << "---------------" << endl;
    B b2(move(b));
    cout << "---------------" << endl;
    return 0;
}

See questions near the two forwards,

Thanks

Foi útil?

Solução

The type of std::forward<T>'s argument is std::remove_reference<T>::type&. Say you pass an object of type X, the compiler knows that std::remove_reference<T>::type should be X. However, how can it determine T? It would have to instantiate std::remove_reference for every possible type (an infinite set) to find out which ones have a type of X. That's why automatic type deduction cannot be done in cases like this.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top