I want to make a function which can handle different kind of things depend on type all in one.
I know Overloading is a nice solution for it. Just like,
class C1 {...};
class C2 {...};
void handle(C1& c1){...}
void handle(C2& c2){...}
But there are so many duplicated code in Overloading way since these 2 initialization is the same. That's why I want to wrap them together.
I have some ideas for my purpose. For example,
class C1 {...};
class C2 {...};
void handle_C1(C1 &c1);
void handle_C2(C2 &c2);
template<typename T>
void handle(T &content){
// Initialization was done here
if (std::is_same(C1, T))
handle_C1(content);
if (std::is_same(C2, T))
handle_C2(content);
}
A compilation error was found error that handle_C2 mismatch parameters because handle_C2 parameter type is C2 when I call
C1 c1;
handle_C1<C1>(c1);
According to SFINAE in C++, I expect the compile would ignore this substitution failed, but it doesn't.
Is there anyone can give me a advice?
Is the best solution overloading? if it's true, how can I reduce my duplicated code.
It seems to me you are overthinking the problem. Simply define overloads without the initialization code and define a handle
function that takes advantage of overload resolution.
class C1 {...};
class C2 {...};
void handle_impl(C1& c1){...} // Remove initialization from your overloads
void handle_impl(C2& c2){...}
template<typename T>
void handle(T &content)
{
// Initialization is done here
// Let the compiler resolve overloads for you
handle_impl(content);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With