use*_*989 5 c++ types declaration
我来自Python,我在管理c ++类型方面遇到了一些问题.在Python中,我可以这样做:
if condition_is_true:
x=A()
else:
x=B()
Run Code Online (Sandbox Code Playgroud)
在程序的其余部分,我可以使用x而不关心x的类型,因为我使用具有相同名称和参数的方法和成员变量(不必使A和B具有相同的基类).现在在我的C++代码中,A类型对应于
typedef map<long, C1> TP1;
Run Code Online (Sandbox Code Playgroud)
和B到:
typedef map<long, C2> TP2;
Run Code Online (Sandbox Code Playgroud)
哪里:
typedef struct C1
{
char* code;
char* descr;
int x;
...
}
Run Code Online (Sandbox Code Playgroud)
和
typedef struct C2
{
char* code;
char* other;
int x;
...
}
Run Code Online (Sandbox Code Playgroud)
C1和C2有类似的成员,在我所说的代码部分中我只需要使用具有相同名称/类型的代码
我想做的事情如下:
if (condition==true)
{
TP1 x;
}
else
{
TP2 x;
}
Run Code Online (Sandbox Code Playgroud)
c ++中的正确方法是什么?
提前致谢
如果条件在编译时已知,则可以使用std::conditional
.这在通用代码中很有用.
typedef std::conditional<
std::is_pointer<T>::value
, TP1
, TP2
>::type map_type;
map_type x;
Run Code Online (Sandbox Code Playgroud)
(测试组成的地方;这里我们测试是否T
是指针类型)
如果在运行时之前无法知道条件,则需要某种形式的动态多态.C++中这种多态性的典型实例是子类型,boost::variant
或者推送时,boost::any
.您应该选择哪一个*以及如何应用它取决于您的总体设计; 我们还不够了解.
*:很可能不会是boost::any
.
我认为你可以通过运行时多态性来做到这一点。
class C_Base { /*all common variables*/ } ;
class C1 : public C_Base { ... };
class C2 : public C_Base { ... };
typedef map<long, C_Base *> TP;
{
...
TP x;
if (condition)
/*use x as if values are C1 * */
else
/*other way round*/
}
Run Code Online (Sandbox Code Playgroud)