简体   繁体   中英

C++ Class object as argument of function

I have two functions in two different files

in file A.cpp

void func(int x, A a){...}

in file B.cpp

void func(int x, B b){...}

These two functions do pretty much the same thing, so I would like to merge them, ie, create a function in file C.cpp who will look like this

void func(int x, AorB c){...} . I don't want my function to look like void func(int x, A a, B b){...}

I'd like to create a class AorB such that my c object is either of type A or B depending on which object I pass to the function.

Templates could help here, if the processing is the same:

template <class X>
void func(int x, X b) {
    ...
}

But beware, templates have to be resolved at compile time, so they have to reside in header files and not in separate compilation units.

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