Search code examples
c++generic-programming

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?


Solution

  • 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