Xun Yang
Xun Yang

Reputation: 4419

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?

Upvotes: 2

Views: 314

Answers (3)

Drew Dormann
Drew Dormann

Reputation: 63775

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)

Upvotes: 2

IronMensan
IronMensan

Reputation: 6831

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*)

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361605

I suppose you could write three individual wrappers. It's equivalent to what the template would produce (i.e. 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 *)

Upvotes: 2

Related Questions