its templates again 😉 Given the following template member functions and CRTP class:
template<typename T>
struct base
{
...
};
struct derived : public base<derived>
{
...
};
struct some_class
{
template<typename T>
void match(base<T>* array, size_t count)
{
...
};
template<typename T, size_t count>
void match(base<T> (&array)[count])
{
...
};
};
Why doesn’t the compiler find a match for the second function:
derived array[10];
some_class foo;
foo.match(array, 10); // works fine
foo.match(array); // Error: no matching function for call to some_class::match(derived array[10])
I would expect the second template function could deduct the compile-time fixde array size, but apparently the function is not considered. Why?
Thanks
Edit: strangely the following version compiles fine:
template<typename T, size_t count>
void match(T (&array)[count])
{
...
};
So I suspect that at some point the original version gets ruled out for some reason I just don’t see.
An array of Derived cannot be converted to an array of Base. If you ever did anything with the array except access the first element in the first constructor, it would be Undefined Behaviour.
Taking the reference correctly protects you from this situation, as the code doesn’t compile. However, it will compile by decaying the array to a single pointer, which can decay to a pointer to Base, which makes the
Base<T>*overload viable, but still bad.