为什么std :: forward不能自己推断模板参数?

时间:2013-12-26 10:25:00

标签: c++ move-semantics

好的,所以我正在玩移动c'tors,我遇到了一个愚蠢的问题, 为什么std :: forward在某些情况下不能推断它自己的参数(假设不​​是继承), 请考虑以下代码:

#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;
}

查看两个前锋附近的问题,

由于

1 个答案:

答案 0 :(得分:1)

std::forward<T>的参数类型为std::remove_reference<T>::type&。假设您传递了X类型的对象,编译器知道std::remove_reference<T>::type应该是X。但是,它如何确定T?它必须为每种可能的类型(无限集)实例化std::remove_reference,以找出哪些类型typeX。这就是为什么在这种情况下不能进行自动类型推导的原因。