简体   繁体   中英

How to judge a value type (int or double) in c++ vector?

I am using a template in C++ to display the vector content in Matlab with mexPrintf . Similar to printf , mexPrintf need an input of the type (%d or %g). As a prior, I know the type of the vector. Do I have a method to judge the type in the template? I want to mexPrintf(" %d", V[i]) for vector<int> , and mexPrintf(" %g", V[i]) for vector<double> .Is it possible? My example code is below.

template<typename  T> void display(T& V)
{
    for (int j = 0; j < V.size(); j++)
    {
        //if
        mexPrintf("\n data is %d\n", V[j]);//int
        //else
        mexPrintf("\n data is %g\n", V[j]);//double
    }
}

I may need the judgement for my if & else . Or any suggestion to another solution?

Since C++17 you can use Constexpr If :

template<typename T> void display(T& V)
{
    for (int j = 0; j < V.size(); j++)
    {
        if constexpr (std::is_same_v<typename T::value_type, int>)
            mexPrintf("\n data is %d\n", V[j]);//int
        else if constexpr (std::is_same_v<typename T::value_type, double>)
            mexPrintf("\n data is %g\n", V[j]);//double
        else
            ...
    }
}

Before C++17 you can provide helper overloads.

void mexPrintfHelper(int v) {
    mexPrintf("\n data is %d\n", v);//int
}
void mexPrintfHelper(double v) {
    mexPrintf("\n data is %g\n", v);//double
}

then

template<typename T> void display(T& V)
{
    for (int j = 0; j < V.size(); j++)
    {
        mexPrintfHelper(V[j]);
    }
}

You can convert the value to a string usingstd::to_string :

template<typename  T> void display(T& V)
{
    for (int j = 0; j < V.size(); j++)
    {
        mexPrintf("\n data is %s\n", std::to_string(V[j]));
    }
}

But you can also just use the standard way of outputting text in C++:

template<typename  T> void display(T& V)
{
    for (int j = 0; j < V.size(); j++)
    {
        std::cout << "\n data is " << V[j] << '\n';
    }
}

In the latest versions of MATLAB std::cout in MEX-files is automatically redirected to the MATLAB console. For older versions of MATLAB you can do this using the trick in this other answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM