Reputation: 113
I have a function in which i am receiving a string values .
Based on the value i want to create a variable.
Template<typename T>
void func( std::string str , T value )
{
if( str == "int" )
{
int val = value;
}
if( str == "double" )
{
double val = value;
}
if( str == "string" )
{
std:string val = value;
}
}
is it possible to automate this function , instead of having lot of if conditions ?
Upvotes: 0
Views: 67
Reputation: 294
You have done great, created a template function
to check the variable type, and then create a variable of that type.
For this, c++11 has introduced the auto
, for variables, specifies that the type of the variable that is being declared will be automatically deduced from its initializer. c++ auto
#include <iostream> // std::cout
#include <string> // std::string
#include <typeinfo> // to check type info
template <typename T>
void func(T value){
auto val = value; // correctly auto deduced type by compiler(since c++11).
std::cout << typeid(val).name() << std::endl; // check the auto deduced type info
}
int main(){
// try
func(12); // output-> i
func(12.3); // output -> d
func("Hello world");
return 0;
}
Upvotes: 1