返回常量模板类型的模板函数

Template function returning a const template type

本文关键字:函数 类型 返回 常量      更新时间:2023-10-16

为什么以下内容不会产生编译器错误?

template<typename T>
const T testFunc()
{
    return T();
}
float* ptr = testFunc<float*>(); // ptr is not const - should be a compiler error!

在这个例子中,testFunc()应该返回一个常量float*,所以当我试图将它分配给一个非常量float*时,不应该出现编译器错误吗?

您的期望值有误,返回的指针将是const,而不是指向的对象。专业化相当于:

float * const testFunc<float*>();

而不是:

float const * testFunc<float*>();

在您的示例中,调用端的代码是从常量指针复制到非常量指针,这很好。