有条件地从函数返回对象类型

conditionally returning an object type from a function

本文关键字:对象 类型 返回 函数 有条件      更新时间:2023-10-16

有没有办法从C++中的函数返回类型?例如,我想使用类似的东西:

// sample pseudo-code: NOT valid C++
template<typename Type1, typename Type2>
type??? getType(bool choice) {
    if(choice == true) {
        return Type1;
    } else {
        return Type2;
    }
}
bool useAwesome = true;
// `Regular` and `Awesome` are classes
getType<Awesome, Regular>(useAwesome) theObject;  

if语句不起作用,因为:

if(useAwesome) {
    Awesome theObject;
} else {
    Regular theObject;
}
// theObject goes out of scope!

我读过"一等公民",知道数据类型不是,但使用template会有所帮助吗?

如果需要在运行时选择类型,通常使用继承:

class Base {};
class Awesome : public Base;
class Regular : public Base;
Base *ObjectPointer;
if (useAwesome)
    ObjectPointer = new Aweseome;
else
    ObjectPointer = new Regular;
Base &theObject = *ObjectPointer;

使用完theObject 后,请务必delete ObjectPointer;(或delete &theObject;)。

请注意,要完成此操作,通常需要定义一个公共接口,以通过其公共基类使用 RegularAwesome 的功能。通常通过在基类中声明(通常是纯)虚函数,然后在派生类中实现这些函数来执行此操作。至少,您需要在基类中声明析构函数 virtual(否则,当您尝试通过指向基的指针删除对象时,您将获得未定义的行为)。

不,你不能那样做。C++中的类型必须在编译时知道,而不是在运行时知道。可以从函数返回typeid,但不能使用该typeid声明相应类型的变量。