有条件地从函数返回对象类型
conditionally returning an object type from a function
有没有办法从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;
)。
请注意,要完成此操作,通常需要定义一个公共接口,以通过其公共基类使用 Regular
或 Awesome
的功能。通常通过在基类中声明(通常是纯)虚函数,然后在派生类中实现这些函数来执行此操作。至少,您需要在基类中声明析构函数 virtual(否则,当您尝试通过指向基的指针删除对象时,您将获得未定义的行为)。
不,你不能那样做。C++中的类型必须在编译时知道,而不是在运行时知道。可以从函数返回typeid
,但不能使用该typeid
声明相应类型的变量。
相关文章:
- 在 C++ 中将一个模板类型的对象类型转换为另一个模板类型
- 了解 Python 中的对象类型
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 调用的对象类型 'double' 不是 report() 函数的函数或函数指针
- 基准、值、值类型、对象和对象类型(C++)
- JNI 如何将 Java 对象数组传递给相同对象类型的 C++ 数组
- 在构造过程中更改的对象类型
- 如何构建程序以避免查询对象类型?
- 如何使用Dynamic_cast获得对象类型
- 什么更有效率?在重载函数中或通过在基类函数中检查对象类型来实现
- static_cast实际上不是对象类型的类型是未定义的行为吗?
- 为什么 std::variant 不能容纳数组对象类型,而联合可以?
- 为什么类型转换对象不会更改其地址?有关对象类型的信息存储在哪里?
- 类返回对象类型,但如何返回和检查 null
- 是否可以在辅助功能中概括对象类型
- 表达式必须在C 中具有指针对象类型
- 下标需要数组或指针类型表达式必须具有指针对象类型
- 当将对象传递给具有参数作为引用类型的函数以及当其类对象类型时,会得到不同的输出
- 如何在运行时指定对象类型
- 我可以获取在重载的新运算符中使用新运算符的对象类型吗?