c++ - 返回 const 模板类型的模板函数

标签 c++ templates pointers constants

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

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/

相关文章:

c++ - 从 Visual Studio 应用程序控制 Unity3D

templates - 如何显示城市和邮政编码?

c - 递归结构(二叉树): obtain values via struct pointer from inside function

c - "cannot convert to a pointer type"C

c++ - 如何在没有 friend 或 C++ 中的 'getter' 函数的情况下从派生类访问抽象私有(private)数据?

c++ - 在派生类上使用工厂方法的模板

c++ - 优化嵌套循环

c++ - 使用 g++ 的成员函数的 undefined reference

C++ 模板专门化以提供额外的成员函数?

c++ - 没有类实例的类成员的地址?