4

I knew C++ template allow function with different datatypes share the similar implementation code, but I was wondering what if the function has totally different execution path depends on the datatypes. Is there anyway to do this?

EvanzzzZ
  • 111
  • 2
  • 9
  • 1
    Template specialization. – jxh May 19 '15 at 17:34
  • Here is an example: http://en.cppreference.com/w/cpp/language/template_specialization – pelya May 19 '15 at 17:36
  • 1
    also see: http://stackoverflow.com/questions/8323530/c-templates-specialization-syntax – NathanOliver May 19 '15 at 17:38
  • 1
    You can specialize or partially specialize templates, use SFINAE, or use overloads, or any combination of them (although combining them can be tricky). – David May 19 '15 at 17:39
  • Do you want to choose at compile time or run time? – Chris Drew May 19 '15 at 17:43
  • Having different execution paths depending on a type is quite common in c++ –  May 19 '15 at 17:48
  • @DieterLücking Yes; virtual functions, function overloading, template specialization... Pretty much every feature of C++ that makes it "C++" is an answer to this question – Nemo May 19 '15 at 17:50
  • @Nemo virtual functions don't have anything to do with this – David May 19 '15 at 17:54
  • 1
    @Dave: Virtual functions are absolutely a mechanism for providing "different execution paths depending on the datatype". In fact that is all they are... – Nemo May 19 '15 at 17:58
  • @Nemo You're twisting the intent of what the op is referring to when he says "datatype". – David May 19 '15 at 18:53
  • 1
    @Dave: Actually I am just making statements that are literally and demonstrably true, not blindly guessing the OP's "intent". C++ provides many mechanisms for dispatching on types; some are compile-time, others are run-time. I do not see why this should be a controversial point. – Nemo May 19 '15 at 19:00
  • @Nemo I wrote a nice explanation, but erased it. I actually think you could see why virtual functions don’t fit as an answer to the OP’s intended question, and that blind guessing isn’t required, if you tried. You’re the type who spends all their energy attacking dissent instead of trying to understand why it might be right. If you respond to this I’m sure it will be as I just described you are. – David May 19 '15 at 20:51
  • @Dave: It's like you've known me for years! Are you some kind of genius? – Nemo May 19 '15 at 21:09

1 Answers1

6

For this you can simply use overloading, you dont need template in this case.

void path(int value)
{
  //
}

void path(string value)
{
  //
}
dynamic
  • 46,985
  • 55
  • 154
  • 231