-2

I'm fighting with C++ language to obtain a mini processor that have four functions: LS(load/store from memory), IC (internal Cash), DE (decode), EX (execute). After I wrote EX function, see below, I`ve found this function must be a parameterized function(?)

EX function looking like this:

void CPU::EX() {

        while (DE_EX.size() != 0) {

            switch (src1) {
            case R0:
                ptrLog->PrintSrc1("R0");
                break;
            case R1:
                ptrLog->PrintSrc1("R1");
                break;
            case R2:
                ptrLog->PrintSrc1("R2");
                break;
            case R3:
                ptrLog->PrintSrc1("R3");
                break;
            case IMM:
                ip = IP + 2;
                ptrLog->PrintSrc1("IMM");
                break;
            case ADDR:
                ip = IP + 2;
                ptrLog->PrintSrc1("ADDR");
                break;
            case ADDR_R:
                ip = IP + 2;
                ptrLog->PrintSrc1("ADDR_R");
                break;
            default:
                ptrLog->PrintSrc1("Not valid");
                break;
            }
    ....
}
Flave
  • 77
  • 1
  • 10
  • 2
    I don't understand what you need to do. What are EX1, EX2 etc supposed to do? How are they called? – Mat Feb 18 '19 at 14:35
  • If I knew, I would not have asked. EX1, EX2 are instances of the EX function. I`m not allowed to rewrite the function, I have to call it somehow - from what I understand using #define EX parameterizable – Flave Feb 18 '19 at 14:42
  • If even you don't know what you're supposed to do, how could we help? – Mat Feb 18 '19 at 14:44
  • Hope someone has encountered this situation and can help me understand – Flave Feb 18 '19 at 14:47

1 Answers1

1

I don't know what difference there would be between EX1 through EX4, but in many cases you can use a function template, if constexpr (instead of #ifdef) and function aliases. The second is a C++17 feature.

Example:

template<bool doA, bool doB>
int f_base() { 
  // common code
  int x = 1;
  if constexpr(doA) {
    x += 2; // some function logic
  }
  // more common code
  x += 3;
  if constexpr(doB) {
    x += 4; // some more conditional logic
  }
  return x;
}

constexpr auto f1 = f_base<false, false>;
constexpr auto f2 = f_base<false, true>;
constexpr auto f3 = f_base<true, false>;
constexpr auto f4 = f_base<true, true>;

int main() {
  return f3();
}
The Vee
  • 11,420
  • 5
  • 27
  • 60