为什么以下不会产生编译器错误?
template<typename T>
const T testFunc()
{
return T();
}
float* ptr = testFunc<float*>(); // ptr is not const - should be a compiler error!
在这个例子中,testFunc() 应该返回一个常量 float*,所以当我尝试将它分配给一个非 const float* 时不应该出现编译器错误吗?
最佳答案
您的期望是错误的,返回的指针 将是常量,而不是指向的对象。特化等同于:
float * const testFunc<float*>();
而不是:
float const * testFunc<float*>();
在您的示例中,调用方的代码是从常量指针复制到非常量指针,这很好。
关于c++ - 返回 const 模板类型的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12170039/