返回常量模板类型的模板函数
Template function returning a const template type
为什么以下内容不会产生编译器错误?
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*>();
在您的示例中,调用端的代码是将从常量指针复制到非常量指针,这很好。
相关文章:
- 为什么在我的函数类型后使用引用运算符 (&) 允许我修改它返回的值?
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 是否有任何建议来统一函数类型限定符并简化可恶的函数类型?
- 关于 C++ 中的函数类型定义
- 用于检测函数类型是否为否的特征
- 函数类型参数的模板参数推导
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- C++无效的函数类型转换
- STL 函数和函数类型与函数指针类型
- 如何将result_of与函数类型定义一起使用
- 将模板(没有规范)传递给 std::thread() 会出现错误:<未解析的重载函数类型>匹配错误
- C++ 编译错误:gnu_printf是无法识别的格式函数类型
- 专门用于"direct"函数类型(与函数指针类型相对)
- 将函数类型作为模板参数传递不会编译
- 通过参数传递 lambda(无函数类型模板)
- 如何在模板参数中分离函数类型返回类型和参数
- 为什么比较函数类型需要指定为模板参数?
- 带有限定符的函数类型定义用例
- 如何声明对函数类型的常量引用
- 非类型模板参数允许各种函数类型?