简体   繁体   中英

C++ wrapping overloaded functions

I want to create a wrap for a bunch of overloaded functions

void print(int i);
void print(long i);
void print(char* s);
...

void myPrint(int x, int y, ??? toPrint){
    moveTo(x,y);
    print(toPrint);
}

How can I do it? Is it possible to go without templates?

If you cannot use templates , you can take the same approach with myPrint that you did with print .

void myPrint(int x, int y, int toPrint){
    moveTo(x,y);
    print(toPrint);
}

void myPrint(int x, int y, long toPrint){
    moveTo(x,y);
    print(toPrint);
}

void myPrint(int x, int y, char* toPrint){
    moveTo(x,y);
    print(toPrint);
}

Since you're doing embedded coding, you could also excuse yourself for using a macro.

#define MYPRINT( x, y, toPrint ) \
    do {                         \
        moveTo(x,y);             \
        print(toPrint);          \
    } while(false)

I suppose you could write three individual wrappers. It's equivalent to what the template would produce (ie a bit of code bloat).

void myPrint(int x, int y, int toPrint) {
    moveTo(x,y);
    print(toPrint);
}

void myPrint(int x, int y, long toPrint) {
    moveTo(x,y);
    print(toPrint);
}

void myPrint(int x, int y, char *toPrint) {
    moveTo(x,y);
    print(toPrint);
}

I don't necessarily recommend this, since code-hiding macros are greatly frowned upon these days, but you could use a preprocessor macro as a template replacement.

#define DEFINE_MY_PRINT(Type)                  \
    void myPrint(int x, int y, Type toPrint) { \
        moveTo(x,y);                           \
        print(toPrint);                        \
    }

DEFINE_MY_PRINT(int)
DEFINE_MY_PRINT(long)
DEFINE_MY_PRINT(char *)

Templates would be preferred, but you can (ab)use the preprocessor:

#define MY_PRINT(T) void myPrint(int x, int y, T toPrint) \
{ \
    moveTo(x,y); \
    print(toPrint); \
}

MY_PRINT(int)
MY_PRINT(long)
MY_PRINT(char*)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM