Home > Blockchain >  Can function templates be instantiated based on the result of runtime if else conditions without cre
Can function templates be instantiated based on the result of runtime if else conditions without cre

Time:12-15

If following is the definition of simple function template:

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

Can it be called with different template parameter based on some user input during runtime, WITHOUT creating class templates, with different T values as follows for example:

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

CodePudding user response:

No. If you want to determine the type at runtime then you need to do what are you doing (the if else)

There are more advanced techniques for more advance uses, like using polymorphism with a table of callables, but in essence they do the same thing, just in a fancier way.

  • Related