C++中不创建class模板,是否可以根据运行时if else条件的结果实例化函数模板?

Can function templates be instantiated based on the result of runtime if else conditions without creating class templates in C++?

如果下面是简单函数模板的定义:

template<typename T>
T compare(T a, T b)
{
   return a>b ? a : b;
}

是否可以在运行时根据某些用户输入使用不同的模板参数调用它,而不创建 class 模板,具有不同的 T 值,例如:

char type;
cout<<"Enter type: ";
cin>>type;

if( type=='i')
{
   int x=compare<int>(3,6);
}
else if( type=='d' )
{
   double z=compare<double>(5.1,7.9);
}
..so on

没有。如果您想在运行时确定类型,那么您需要做您正在做的事情(if else)

有更高级的技术用于更高级的用途,例如将多态与 table 可调用对象一起使用,但本质上它们做同样的事情,只是方式更奇特。