为什么C 模板功能不支持返回指针
why C++ template function do not support returning a pointer?
我具有这样的函数:
#include <iostream>
using namespace std;
// function to generate and retrun random numbers.
template<typename T>
T * getRandom( ) {
static T r[10];
for (int i = 0; i < 10; ++i) {
r[i] = 111;
cout << r[i] << endl;
}
return r;
}
// main function to call above defined function.
int main () {
// a pointer to an int.
int *p;
p = getRandom();
for ( int i = 0; i < 10; i++ ) {
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
return 0;
}
但是,当我使用G 5.4和C 11编译代码时。编译器给我这个错误:
main.cpp: In function 'int main()':
main.cpp:25:18: error: no matching function for call to 'getRandom()'
p = getRandom();
^
main.cpp:25:18: note: candidate is:
main.cpp:8:5: note: template<class T> T* getRandom()
T * getRandom( ) {
^
main.cpp:8:5: note: template argument deduction/substitution failed:
main.cpp:25:18: note: couldn't deduce template parameter 'T'
p = getRandom();
^
看来C 不支持将指向模板指向的指针返回?
任何人都可以告诉我我的玩具示例怎么了,谢谢!
模板参数不能从返回类型中推导,而只能从函数参数中推导。因此,您必须明确指定模板参数。例如
p = getRandom<int>();
// ~~~~~
相关文章:
- 为什么istream不支持右值提取
- 为什么模板类中的对象不能返回值
- C++Brute Force攻击函数不会返回结果
- 我可以使用什么来停止循环而不是"返回 0"?
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 错误:(-210:不支持的格式或格式组合)功能'create'中的硬件视频解码器不支持视频源
- 从 cin 读取不会返回整个输入字符串
- GetTokenInformation 在非提升时不会返回所有特权的雕像
- Casablanca/cpprestsdk listener.support接受函数,但不支持方法
- 为什么C++不支持对未初始化变量进行智能分析?
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 在 Ubuntu 18.04 上编译 GLSL 着色器时"不支持 GLSL 3.30"?
- 为什么联机C++ IDE 不支持"graphics.h"头文件?
- 为什么我不能返回带有透明函子的法线映射引用?
- 在 Linux 中关闭 UDP 套接字后,recv 不会返回
- Clang编译器不支持aarch64-apple-darwin上的-fxray-instrument
- 为什么我的 clang 格式不支持 PPDirectiveIndentStyle 选项?
- 为什么C 模板功能不支持返回指针
- createProcessWithLogon返回不支持的函数
- fmod音频.setMusicSpeed返回不支持的格式错误