为什么C 模板功能不支持返回指针

why C++ template function do not support returning a pointer?

本文关键字:不支持 返回 指针 功能 为什么      更新时间:2023-10-16

我具有这样的函数:

#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>();
//           ~~~~~