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

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

问题描述

我正在实现一个 BOOOS - 基本面向对象操作系统,现在我需要让我的程序的调度程序在 FCFS 和优先级之间进行选择.我有一个名为 Task 的类,我在其中创建了两个队列:std::queue 和一个 std::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 调度器,我使用没有优先级的调度器,如果用户想要一个优先级调度器,我使用 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;

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

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