2

I have a function which can match std::vector and other containers well:

template <typename T, typename... Rest,
          template <typename, typename...> class Container>
std::string DoSomethingOnContainer(Container<T, Rest...> vals) {
  // do something
}

But it cannot match std::array, e.g. std::array<int, 10>. How to make the function also match std::array?

I am using c++17.

IvanaGyro
  • 598
  • 7
  • 25
  • This should do it: https://stackoverflow.com/questions/17156282/passing-a-stdarray-of-unknown-size-to-a-function – Florin C. Jan 24 '22 at 05:46
  • 1
    On naive idea: Can we use "template std::string DoSomethingOnContainer(C vals) { ... }" in your case? Or can we make a specialized method specific for `std::array`? – Zhao Yunjian Jan 24 '22 at 05:48
  • Remeber C++ templates are expanded at compiler time. – Zongru Zhan Jan 24 '22 at 05:50
  • 3
    Reason matching fails is in `std::array` the second parameter is **not** type but a value(like 1, 2, 3 etc.). Create a different overload for `std::array` maybe? or something like @ZhaoYunjian mentioned. – Ch3steR Jan 24 '22 at 05:50
  • this is a fundamental limitation of C++ templates. `auto…` or something like that (i don’t remember) was proposed in order to cover this case. most likely i would go with another overload or not use template templates at all and rely of afinae (e.g. mention Container::iterator) or concepts. – alfC Jan 24 '22 at 06:24
  • 2
    `template std::string DoSomethingOnContainer(Container vals) { using T = typename Container::value_type; /* do something */ }` might be a good alternative. – Jarod42 Jan 24 '22 at 09:24

0 Answers0