Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different value depending on type C++

I'd like to have different variable value depending on type of input variable. Code:

template <typename T>
int getValue(vector<T> & data)
{
    return something; // There should be 0 for int and 1 for double
}

Do anyone know how to achieve such a functionality?

like image 382
miqelm Avatar asked Feb 08 '23 20:02

miqelm


1 Answers

If you are just dealing with an int and double then you could just overload the function for the differnt types of vectors.

int getValue(vector<int> & data)
{
    return 0;
}

int getValue(vector<double> & data)
{
    return 1;
}

If you want to keep getValue as a template function and specialize for int and double then you could use

template<typename T>
int getValue(std::vector<T> & data)
{
    return -1;
}

template <>
int getValue(std::vector<int> & data)
{
    return 0;
}

template <>
int getValue(std::vector<double> & data)
{
    return 1;
}

Live Example

like image 88
NathanOliver Avatar answered Feb 16 '23 03:02

NathanOliver