如何判断 c++ 向量中的值类型(整数或双精度)?

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

本文关键字:整数 类型 双精度 向量 何判断 判断 c++      更新时间:2023-10-16

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

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

我可能需要对我的ifelse做出判断。或者对其他解决方案有任何建议?

从 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 %dn", V[j]);//int
else if constexpr (std::is_same_v<typename T::value_type, double>)
mexPrintf("n data is %gn", V[j]);//double
else
...
}
}

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

void mexPrintfHelper(int v) {
mexPrintf("n data is %dn", v);//int
}
void mexPrintfHelper(double v) {
mexPrintf("n data is %gn", 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 %sn", 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,您可以使用另一个答案中的技巧来执行此操作。