2

有没有办法从 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某种方式使用帮助吗?

4

2 回答 2

2

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

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(否则,当您尝试通过指向基类的指针删除对象时,您将获得未定义的行为)。

于 2012-12-08T12:31:51.087 回答
1

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

于 2012-12-08T12:29:35.593 回答