Why doesn’t the following produce a compiler error?
template<typename T>
const T testFunc()
{
return T();
}
float* ptr = testFunc<float*>(); // ptr is not const - should be a compiler error!
In this example, testFunc() should be returning a constant float*, so shouldn’t there be a compiler error when I try to assign it to a non-const float* ?
You are wrong on your expectations, the returned pointer will be const, not the object pointed. The specialization is equivalent to:
Rather than:
In your example, the code at the call side is copying from a const pointer to a non-const pointer, which is fine.