Domanda

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

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top