Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从函数有条件地返回对象类型 有什么方法可以从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;_C++_Templates_C++03 - Fatal编程技术网

从函数有条件地返回对象类型 有什么方法可以从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;

从函数有条件地返回对象类型 有什么方法可以从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;,c++,templates,c++03,C++,Templates,C++03,我读过关于“一等公民”的书,知道数据类型不是,但是使用模板会有帮助吗 不,你不能那样做。C++中的类型必须在编译时知道,而不是在运行时。可以从函数返回typeid,但不能使用该typeid来声明相应类型的变量。如果需要在运行时选择类型,通常使用继承: class Base {}; class Awesome : public Base; class Regular : public Base; Base *ObjectPointer; if (useAwesome) ObjectP

我读过关于“一等公民”的书,知道数据类型不是,但是使用
模板
会有帮助吗

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

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

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;


请注意,要实现这一点,通常需要定义一个公共接口,通过它们的公共基类使用
常规
Awesome
的功能。您通常会在基类中声明(通常是纯的)虚拟函数,然后在派生类中实现这些函数。至少,您需要在基类中声明析构函数virtual(否则,当您试图通过指向基类的指针删除对象时,您将得到未定义的行为)。

C++是静态类型的。所有类型都必须在编译时已知。如果只在运行时确定了
选项
,则这不起作用。即使假定
对象
仍在范围内,也很难想象在
选项
之后有一个共同的路径:如果类型足够不同,则对
对象
对象所做的事情对两者都有意义。
class Base {};

class Awesome : public Base;
class Regular : public Base;

Base *ObjectPointer;

if (useAwesome)
    ObjectPointer = new Aweseome;
else
    ObjectPointer = new Regular;

Base &theObject = *ObjectPointer;