Der*_*urn 5 c++ dynamic dynamic-typing c++11
在C#4.0中,您可以使用"dynamic"关键字作为占位符,直到运行时才知道该类型.在某些极端情况下,这是非常有用的行为.是否有可能在C++中模拟这样的事情,可能使用C++ 0x功能或RTTI?
并不真地。您可以获得的最接近的是 a void *,但您仍然需要将其转换为适当的类型,然后才能使用它。
更新:
基本上,尝试构建一个可编译为 C++ 的鸭子类型 DSL。
您至少可以通过两种方式来解决此问题:
基于联合的变体
struct MyType {
enum { NUMBER, STRING /* etc */ } type;
union {
double number;
string str;
};
};
Run Code Online (Sandbox Code Playgroud)
多态类层次结构
class MyType {
public:
/* define pure virtual operations common to all types */
};
class MyNumber : public MyType {
private:
double number;
public:
/* implement operations for this type */
};
Run Code Online (Sandbox Code Playgroud)