0

I have a function that takes in a parameter with generic type T. And it will do different things depending on the type of obj.

template <typename T>
void function(const T& obj)
{
    if constexpr (/* is a vector */) {}
    else if constexpr (/* is an unordered map */) {}
    // ...
    else {}
}

So I need to check if the type of obj is vector, or unordered_map, or unordered_set, etc.

Anyone knows the answer to this? Thanks!

Luan Truong
  • 134
  • 5
  • 4
    Since it looks like every type has different behavior, the easiest solution is probably to have overloads of `function` for each supported type instead. Ex. `template void function(const std::vector& obj);`. – François Andrieux Aug 16 '22 at 19:33
  • 9
    *"I have a function that takes in a parameter with generic type T. And it will do different things depending on the type of obj." - thereby completely defeating the very point of a "generic type T". Consider overloads with specific container types, lest you fall into a function full of spaghetti as more container types are added. – WhozCraig Aug 16 '22 at 19:35
  • Reopened. The claimed duplicate is about a completely different issue. – Pete Becker Aug 16 '22 at 20:04
  • 3
    Don't check. Write overloads. `template void f(const T&) { ... } template void f(const std::vector&) { ... }`. Etc. – Pete Becker Aug 16 '22 at 20:05
  • Does it do completely different things, or the same thing in different ways? If it does completely different things, then maybe it should be two functions ("sort_vector" and "filter_map"). If it does the same thing in different ways, maybe you can genericize the implementation so it works for both. – Raymond Chen Aug 16 '22 at 20:09
  • In this case, as `std::vector`, `std::unordered_map`, etc. are clearly distinct types, I agree it could be easier with overloads. But in our company code base, I was able to simplify a lot some core functions like `toPOD`. Previously, that function was written as a bunch of overloaded complicated templates with `std::enable_if_t`, and it is a lot easier in a single function as a sequence of `if constexpr... else if constexpr`. What I particular find powerful in this approach, is that we guarantee that there is no ambiguity, the order of tests discriminates. – prapin Aug 16 '22 at 20:27

1 Answers1

0

Thanks for all the comments. I have written overloads and it is now working perfectly :)

Luan Truong
  • 134
  • 5