条件变量声明 [英] Conditional variable declaration

查看:106
本文介绍了条件变量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自Python,在使用c ++管理类型时遇到一些问题。在Python中,我可以执行以下操作:

I'm coming from Python and I have some problem with managing types in c++. In Python I can do something like this:

if condition_is_true:
    x=A()
else:
    x=B()

在程序的其余部分中,我可以使用x而不关心关于x的类型,假设我使用具有相同名称和参数的方法和成员变量(A和B不必具有相同的基类)。
现在在我的C ++代码中,类型A对应于

and in the rest of the program I can use x without caring about the type of x, given that I use methods and member variables with the same name and arguments (not necessary that A and B have the same base classes). Now in my C++ code type A corresponds to

typedef map<long, C1> TP1;

和B到:

typedef map<long, C2> TP2;

其中:

typedef struct C1
{
    char* code;
    char* descr;
    int x;
...
}

typedef struct C2
{
    char* code;
    char* other;
    int x;
...
}

C1和C2具有相似的成员,并且在我要讲的部分代码只需要使用相同名称/类型的代码即可

C1 and C2 have similar members and in the part of code I'm talkin of I only have to use the ones with the same name/type

我想执行以下操作:

if (condition==true)
{
    TP1 x;
}
else
{
    TP2 x;
}

在c ++中正确的方法是什么?

what is the correct approach in c++?

预先感谢

推荐答案

如果在编译时知道该条件,则可以使用 std :: conditional

If the condition is known at compile-time, you can use std::conditional. This is useful in generic code.

typedef std::conditional<
    std::is_pointer<T>::value
    , TP1
    , TP2
>::type map_type;
map_type x;

(其中测试已完成;这里我们正在测试 T 是否是指针类型)

(where the test is made-up; here we're testing whether T is a pointer type or not)

如果直到运行时才知道条件,则需要某种形式的动态多态。在C ++中,这种多态性的典型实例是子类型化 boost :: variant 或当推送被推送时, boost :: any 。您应该选择哪种*以及如何应用它取决于您的总体设计;我们还不够了解。

If the condition cannot be known until runtime, then some form of dynamic polymorphism is needed. Typical instances of such polymorphism in C++ are subtyping, boost::variant or when push comes to shove, boost::any. Which one you should pick* and how you should apply it depends on your general design; we don't know enough.

*:很有可能 not boost :: any

这篇关于条件变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆