繁体   English   中英

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

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

我在 C++ 中使用模板来显示带有mexPrintf的 Matlab 中的矢量内容。 printf类似, mexPrintf需要输入类型(%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 如果

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 中,MEX 文件中的std::cout会自动重定向到 MATLAB 控制台。 对于旧版本的 MATLAB,您可以使用其他答案中的技巧来执行此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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