我使用 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/