【发布时间】:2018-08-05 19:22:55
【问题描述】:
我想出了一个 C++ 运行时多态性的解决方案。
#include <iostream>
using namespace std;
class base {
public:
virtual void call(double xx) {
cout << "DERIVED: " << xx << endl;
}
};
template<typename T>
class derivedT : base {
public:
virtual void call(double xx) {
cout << "DERIVED_T: " << ((T) xx) << endl;
}
};
int main() {
base* sample = nullptr;
cout << "CHOOSE TYPE: (BYTE = 1, UINT = 2, DOUBLE = 3)" << endl;
uint8_t type = cin.get();
type -= 48;
switch (type) {
case 1:
sample = (base*) new derivedT<uint8_t>();
break;
case 2:
sample = (base*) new derivedT<uint32_t>();
break;
case 3:
sample = (base*) new derivedT<double_t>();
break;
}
sample->call(2567.45);
cin.get();
cin.get();
}
这里的想法是编译器将在运行时在 switch 语句中生成所有模板化类型。 模板在编译时是已知的,所以现在我们可以从在派生类中被覆盖的虚拟基类。
唯一可行的原因是每个类的函数具有相同的参数。如果我们要在使用 T 的派生类中使用参数,那么它将不起作用。因此,我们将参数转换为派生类中的 T 以实现所需的行为。我注意到这只适用于 C 风格的转换。
Soo...这里发生了什么样的未定义行为?
【问题讨论】:
-
“编译器将在运行时生成所有模板化类型”:不,它将在编译时生成所有模板实例化。
switch只会选择在运行时使用哪一个。
标签: c++ templates inheritance polymorphism c++17