如何判断c++ vector中的值类型(int或double)?

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

我正在使用 C++ 中的模板在带有 mexPrintf 的 Matlab 中显示矢量内容。类似于 printfmexPrintf 需要输入类型(%d 或 %g)。作为先验,我知道向量的类型。有没有方法判断模板中的类型?我想 mexPrintf(" %d", V[i])vector<int>mexPrintf(" %g", V[i])vector<double>。可以吗?我的示例代码如下。

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
    }
}

我的 if & else 可能需要判断。或者对其他解决方案有什么建议吗?

从 C++17 开始你可以使用 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
            ...
    }
}

在 C++17 之前,您可以提供帮助程序重载。

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

然后

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

您可以使用 std::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]));
    }
}

但您也可以只使用 C++ 中输出文本的标准方式:

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

在最新版本的 MATLAB std::cout 中,MEX 文件会自动重定向到 MATLAB 控制台。对于旧版本的 MATLAB,您可以使用 this other answer.

中的技巧来完成此操作