Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ alternative for macro pasting

Tags:

c++

macros

Let's say i have a series of classes:

class Port8Bit{
    void Write(uint8_t data);
    uint8_t Read();
};

class Port16Bit{
    void Write(uint16_t data);
    uint16_t Read();
};
//and so on for 32Bit and 64Bit

when i want to initiate the classes, instead of writing the code again for each class, i can use a macro:

#define intiatePort(portSize) { \
Port##portSize##Bit::Port##portSize##Bit(){ \
} \
  \
void Port##portSize##Bit::Write(uint##portSize##_t data){ \
  \  //write data 
} \
uint##portSize##_t Port##portSize##Bit::Read(){ \
    uint##portSize##_t result; \
    \    //read data 
    return result;  \

}

I'm quite new to CPP, but I've read that using macros in most cases is not a good practice. I would like to know, is there a better, more CPP-ish way of doing this?

like image 585
ofir dubi Avatar asked Dec 09 '25 17:12

ofir dubi


1 Answers

That's what templates are for:

template<class DataType>
class Port{
    void Write(DataType data);
    DataType Read();
};

using Port8Bit = Port<uint8_t>;
using Port16Bit = Port<uint16_t>;
// etc...
like image 98
zdan Avatar answered Dec 11 '25 16:12

zdan