Dav*_*vid 2 c++ polymorphism inheritance pointers generic-programming
在这段代码中,为什么typename T(在Test(...)函数中)评估为键入Foo而不是类型Bar?我怎样才能改变它以使它成为Bar型?
#include <typeinfo>
using namespace std;
struct Foo
{
virtual ~Foo() { }
};
struct Bar : public Foo
{
};
template<typename T>
bool Test(T foo)
{
return (typeid(foo) == typeid(Bar));
}
int main()
{
Bar bar;
Foo *foo = &bar;
bool THIS_IS_TRUE = (typeid(*foo) == typeid(Bar));
bool WHY_ISNT_THIS = Test(*foo);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
模板是基于静态类型而不是动力类型推导出来的.代码是静态绑定的,并根据编译器在编译时知道的内容创建,与运行时的类型无关.此外,当您通过*foo值传递时,无论如何都要对对象进行切片.
| 归档时间: |
|
| 查看次数: |
245 次 |
| 最近记录: |