【发布时间】:2021-01-28 12:06:32
【问题描述】:
我在 Animal 命名空间中有一个类 AnimalInterface:
namespace Animal
{
class AnimalInterface
{
public:
AnimalInterface() = default;
virtual ~AnimalInterface() = default;
virtual std::string makeSound() = 0;
};
}
假设我有 2 个从这个接口实现的类
class Dog : public AnimalInterface
{
public:
Dog() = default;
~Dog() = default;
std::string makeSound()
{
return "Bark";
}
};
class Cat : public AnimalInterface
{
public:
Cat() = default;
~Cat() = default;
std::string makeSound()
{
return "Meow";
}
};
现在我有了一个调用这些函数的类。我希望能够使用运行时类型信息从对象中获取动物的类名。
void AnimalSounds
{
list<unique_ptr<AnimalInterface>> animals;
animals.push_back(make_unique<Dog>());
animals.push_back(make_unique<Cat>());
for (const auto& animal : animals)
{
cout << typeid(animal).name() << " makes sound: " << animal->makeSound() << endl;
}
}
我希望输出是
Dog makes sound: Bark
Cat makes sound: Meow
相反,我得到以下内容
class std::unique_ptr<class Animal::AnimalInterface,struct std::default_delete<class Animal::AnimalInterface> > makes sound: Bark
class std::unique_ptr<class Animal::AnimalInterface,struct std::default_delete<class Animal::AnimalInterface> > makes sound: Meow
我该如何解决这个问题?谢谢!
【问题讨论】:
-
我希望能够使用反射从对象中获取动物的类名。 -- 目前在 C++ 中没有反射。这看起来像 XY Problem
-
typeid返回的字符串是实现定义的。 stackoverflow.com/questions/1986418/typeid-versus-typeof-in-c -
想想
animal是什么类型。真的是Dog还是Cat?无论如何,您不能依赖typeid(...).name(),它的输出既不能保证是类名,也不能保证是一致的(甚至在同一个程序的执行之间也不行)。 -
怎么样--
std::unordered_map<std::string, std::unique_ptr<AnimalInterface>>或者动物可以有重复的名字std::unordered_multimap<std::string, std::unique_ptr<AnimalInterface>>?
标签: c++ reflection unique-ptr