forward到基类的类型,编译异常,为什么
forward到基类的类型,编译错误,为什么
尝试用forward把一个继承类Derived的实例, 转发给一个接受Base类型的函数,如下:
gcc给出了如下错误信息:
看起来f(Derived())是编译不过的。forward是可以接受不同的类型作为模板参数的, 向上转型难道不行吗, 还是我的理解有误
------解决思路----------------------
没有继承怎么叫向上转型了?
尝试用forward把一个继承类Derived的实例, 转发给一个接受Base类型的函数,如下:
#include<iostream>
using namespace std;
struct Base{
Base(){ cout << "Base ctor" << endl; }
Base(const Base&){ cout << "Base copy ctor" << endl; }
Base(Base&&){ cout << "Base move ctor" << endl; }
};
struct Derived{
Derived(){ cout << "Derived ctor" << endl; }
Derived(const Derived&){ cout << "Derived copy ctor" << endl; }
Derived(Derived&&){ cout << "Derived move ctor" << endl; }
};
void g(Base&&)
{
cout << "called f Base" << endl;
}
template<class T>
void f(T&& t)
{
g(forward<Base>(t));
}
int main()
{
f(Derived());
return 0;
}
gcc给出了如下错误信息:
||=== Build: Debug in my (compiler: GNU GCC Compiler) ===|
D:\Documents\my\main.cpp||In instantiation of 'void f(T&&) [with T = Derived]':|
D:\Documents\my\main.cpp|24|required from here|
D:\Documents\my\main.cpp|20|error: no matching function for call to 'forward(Derived&)'|
D:\Documents\my\main.cpp|20|note: candidates are:|
c:\program files (x86)\codeblocks\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\move.h|76|note: template<class _Tp> constexpr _Tp&& std::forward(typename std::remove_reference<_From>::type&)|
c:\program files (x86)\codeblocks\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\move.h|76|note: template argument deduction/substitution failed:|
D:\Documents\my\main.cpp|20|note: cannot convert 't' (type 'Derived') to type 'std::remove_reference<Base>::type& {aka Base&}'|
c:\program files (x86)\codeblocks\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\move.h|87|note: template<class _Tp> constexpr _Tp&& std::forward(typename std::remove_reference<_From>::type&&)|
c:\program files (x86)\codeblocks\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\move.h|87|note: template argument deduction/substitution failed:|
D:\Documents\my\main.cpp|20|note: cannot convert 't' (type 'Derived') to type 'std::remove_reference<Base>::type&& {aka Base&&}'|
||=== Build failed: 1 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|
看起来f(Derived())是编译不过的。forward是可以接受不同的类型作为模板参数的, 向上转型难道不行吗, 还是我的理解有误
------解决思路----------------------
没有继承怎么叫向上转型了?