4

I have a question related to templates.

template <typename A, typename B>
void someFunction (A* array, const B& numEl);

I want numEl (-->numberOfElements) to be unsigned, but const unsigned won't compile. Number of elements in an array is never a negative number and I will always be using long, int or short so it makes sense for me to make numEl unsigned

BR41N-FCK
  • 766
  • 6
  • 17
  • 1
    "numEl (-->numberOfElements)" Why not just...write out the full name in code? If you have to explain it here, you should just explain it in code. Your compiler will handle the name just fine. And you need to define "won't compile". – GManNickG Apr 13 '13 at 20:21

1 Answers1

4

If you only want the user to call your function with unsigned types, you could use something like this:

template<typename A, typename B, typename = typename std::enable_if<std::is_unsigned<B>::value>::type>
void someFunction(A * array, B numEl) {
    // do something
}

Also note that since you are dealing with integral types for B, there is no need to accept numEl as const reference.

POC on ideone

Tom Knapen
  • 2,277
  • 16
  • 31
  • There's a need for it to be a const reference. const- because I don't make modifications to it, reference- to avoid wasting time it takes to make a copy of the passed variable. Thank you very much! To be honest, I have no idea how this thing works. Can you suggest a webpage or a book to learn it? I think I could do with a book describing some advanced features/techniques available in C++. There's a ton of books on basics, but haven't found any on advanced or even intermediate things like usage of typedef with templates, traits (don't know what it is, cuz I haven't found any resource on it). – BR41N-FCK Apr 14 '13 at 08:57