【问题标题】:If we return a variable from a template function and we don't know what will be its data type how to get this returned variable in main function如果我们从模板函数返回一个变量,并且我们不知道它的数据类型是什么,如何在主函数中获取这个返回的变量
【发布时间】:2021-10-22 17:23:55
【问题描述】:
#include<iostream>
using namespace std;

template<class T>
T func()
{
   T a;
   cout<<"Enter value of a : ";
   cin>>a;
   return a;
}

int main()
{
    void*ptr;
    ptr=&func<void>();
    // How to get returned value from template function as i don't know what
    // will its data type???
    return 0;
}

【问题讨论】:

  • 它将是无效的,因为您将 void 作为T 传递。但它不会编译。
  • 这就是auto 派上用场的地方:auto value = func&lt;T&gt;();。请注意,类型仍然在编译时分配,您不必再次键入它。您的代码错误 - 获取临时变量的地址将使 ptr 无法使用。
  • 如何解决这个问题我想获取未知变量,我不知道它的数据类型是 int 还是 string 或者 float 还是 char 我不知道因为函数是模板所以如何获得这个值?

标签: c++ function templates


【解决方案1】:

您确实知道函数模板返回什么类型,因为您将返回类型指定为类型参数。也就是说,您可以使用类型推导占位符auto 让编译器推导出该类型:

int main()
{
    auto value = func<int>();
    // same as:
    //int value = func<int>();
}

您无法实例化模板func&lt;void&gt;,因为模板创建了T 类型的变量,并且无法创建void 变量。

【讨论】:

    【解决方案2】:

    例如使用关键字'auto'

    #include <string>
    
    template<typename F>
    auto call(F f) 
    {
        return f();
    }
    
    std::string Hello()
    {
        return std::string("Hello");
    }
    
    int main()
    {
       int value = call([](){ return 42; }); // or also use auto value =
       std::string hello = call(Hello);      // or also use auto hello = 
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-09
      • 2014-10-23
      • 2021-05-13
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      相关资源
      最近更新 更多