![](/img/trans.png)
[英]How to call any class function using its pointer if we know arguments and return type?
[英]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
#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;
}
您確實知道 function 模板返回什么類型,因為您將返回類型指定為類型參數。 也就是說,您可以使用類型推導占位符auto
讓編譯器推導該類型:
int main()
{
auto value = func<int>();
// same as:
//int value = func<int>();
}
你不能實例化模板func<void>
因為模板創建了一個T
類型的變量,而void
變量不能被創建。
例如,使用關鍵字“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 =
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.