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

标签 c++ matlab templates stdvector mex

我使用 C++ 中的模板在 Matlab 中显示 vector 内容 mexPrintf .类似于 printf , mexPrintf需要类型的输入(%d 或 %g)。作为先验,我知道 vector 的类型。有没有方法判断模板中的类型?我要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]);
    }
}

关于c++ - 如何判断c++ vector中的值类型(int或double)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58262894/

相关文章:

c++ - 使用 boost lib 的更高精度 float (高于 16 位数字)

excel - Matlab:使用 Matlab 复制 Excel 表并删除定义的 EXCEL 名称

matlab - 显示冲浪的实际尺寸?

c++ - 查找模板类型的模板类型 C++

c++ - `std::function` 和之前推导的模板参数的替换失败 - 为什么?

c++ - 从 C++ 调用 Haskell 库

c++ - 如何将数组的所有元素更改为特定值?

c# - 当在 C/C# 等中实现相同的滤波器/代码时,matlab IIR 滤波器会给出不同的输出

c++ - 使用模板避免类似的功能

c++ - 创建没有最大化按钮且没有调整大小选项的窗口框架?