Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a specific function depend on type

Tags:

c++

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.

like image 683
Rick Avatar asked Aug 04 '17 14:08

Rick


1 Answers

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);
}
like image 126
François Andrieux Avatar answered Sep 27 '22 21:09

François Andrieux