【发布时间】:2019-04-10 04:21:36
【问题描述】:
我正在尝试将一个对象转换为类,如果它是从另一个特定类派生的,还是在模板方法中转换为基本类型(int、float string 等),但我得到了同样的错误。
代码:
#include <string>
#include <iostream>
//Base class
class A
{
public:
virtual ~A() = default;
std::string Get() {
return "A";
};
};
//Derived class
class B : public A
{
public:
virtual ~B() = default;
std::string Get() {
return "B";
};
};
class C
{
public:
template <typename T>
void Echo(T* t)
{
if (std::is_base_of<A, T>::value)
{
//complex types, derived from A
std::cout << dynamic_cast<A*>(t)->Get();
}
else
{
//basic types(int, float, string etc...)
std::cout << *t;
}
}
};
int main()
{
C c;
c.Echo(new int(12345));
c.Echo(new B());
return 0;
}
错误:
error: cannot dynamic_cast ‘t’ (of type ‘int*’) to type ‘class A*’ (source is not a pointer to class)
error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘B’)
.
.
.
有没有人知道如何做这样的事情,谢谢?
【问题讨论】:
标签: c++ templates inheritance casting