我在mexPrintf中使用C++中的一个模板来显示矢量内容。与printf类似,mexPrintf需要类型为(%d或%g)的输入。作为先验,我知道向量的类型。我有没有方法来判断模板中的类型?我想为vector<int>使用mexPrintf(" %d", V[i]),而为vector<double>.Is使用mexPrintf(" %g", V[i]),这是可能的吗?我的示例代码如下。
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的判断。或者对其他解决方案有什么建议?
发布于 2019-10-07 11:33:25
可以使用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,您可以使用this other answer中的技巧来完成此操作。
发布于 2019-10-07 10:48:01
既然是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]);
}
}https://stackoverflow.com/questions/58262894
复制相似问题