是否可以在函数外部(例如main)使用if语句? [英] Is it possible to use if statement outside a function (like main)?

查看:242
本文介绍了是否可以在函数外部(例如main)使用if语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现BOOOS-基本的面向对象的操作系统,现在需要使程序的调度程序在FCFS和Priority之间进行选择.我有一个名为Task的类,在其中创建两个队列:std::queuestd::priority_queue.这些队列是在Task.h中声明的静态成员,我需要在初始化Task.cc中的其他成员之前,先与该类的其他静态成员进行初始化,例如:

I'm implementing a BOOOS - Basic oriented-Object Operational System, and now I need to make my program's scheduler choose between FCFS and Priority. I have a class called Task, where I create two queues: std::queue and a std::priority_queue. Those queues are static members declared in Task.h, and I need to initialize then before any other thing in the Task.cc with the others static members of the class, like this:

namespace BOOOS {

    volatile Task * Task::__running;
    Task * Task::__main;
    int Task::__tid_count;
    int Task::__task_count;
    std::queue<Task*> Task::__ready;
    std::priority_queue<Task*> Task::__ready;

    (rest of the Task.cc)

}

您可以看到我有两个__ready队列.这就是为什么我只需要使用其中之一的原因.如果用户要初始化FCFS Scheduler,则使用无优先级的FCFS Scheduler,如果用户需要优先级Scheduler,则使用priority_queue.这是由BOOOS的静态枚举成员控制的.所以,这是我的问题:我是否可以在代码的这一部分中使用与if类似的东西来选择一个队列,而不是创建两个队列,并且每次需要在程序中进行操作时都创建一个if?

You can see that I have two __ready queues. That's why I need to use only one of then. If the user want to initialize a FCFS Scheduler, I use the one with no priority, and if the user want a priority Scheduler, I use the priority_queue. This is controlled by a BOOOS's static enum member. So, here's my question: Can I use something similar to if in this part of the code to choose only one queue instead of creating two and make an if everytime I need to manipulate it in my program?

推荐答案

不能,通过使用if()语句是不可能的.这些实际上需要放置在功能体内.

No that's not possible through using an if() statement. These need to be placed inside a function body actually.

您的选择是

  • 使用C预处理器并拥有

  • use the C-preprocessor and have a

#if !defined(USE_PRIORITY_QUEUE)
std::queue<Task*> Task::__ready;
#else
std::priority_queue<Task*> Task::__ready;    
#endif

预处理程序指令.

使用模板类和专业化

template<bool use_priority_queue>
struct TaskQueueWrapper {
     typedef std::queue<Task*> QueueType;
};

template<>
struct TaskQueueWrapper<true> {
     typedef std::priority_queue<Task*> QueueType;
};

TaskQueueWrapper<true>::QueueType Task::__ready;

这篇关于是否可以在函数外部(例如main)使用if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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