假设我有这样一个类结构:基类Object,它是Bool、Int、Float和类Bytes的父Unicode类。在我在类和所有子类中将一些函数(如Bool cast_bool() const、Int cast_int() const等)作为虚函数之前,Object我已经分别实现了这些函数。
似乎更好的解决方案是实现template <typename TYPE> TYPE cast() const功能。但是,由于 C++ 禁止虚拟模板功能,我不知道如何才能完成这项任务。我需要的是提供template <typename TYPE> TYPE cast() const和Object它的孩子。泛型Object::cast<TYPE>() const只会抛出CastError;然后对于每种类型,如Bool,Int等。我将实现,等函数Bool::cast<Bool>() const。Int::cast<Bool>() const我什至计划将强制转换添加到内置对象,尽管现在我只是重载operator bool() const,operator signed short() const等。如果没有实现,模板必须切换到它来自类的通用形式Object,只是抛出一个错误。有没有办法做到这一点(也许我需要使用一些模式)?或者更容易留下类似的功能Int cast_int() const?提前致谢!