我正在使用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
进行判断。或对其他解决方案有何建议?
答案 0 :(得分:4)
自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]);
}
}
答案 1 :(得分:3)
您可以使用std::to_string
将值转换为字符串:
protected $fillable = [
'name',
'is_delete'
];
但是您也可以使用在C ++中输出文本的标准方法:
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]));
}
}
在MEX文件的最新版本的MATLAB template<typename T> void display(T& V)
{
for (int j = 0; j < V.size(); j++)
{
std::cout << "\n data is " << V[j] << '\n';
}
}
中,该文件会自动重定向到MATLAB控制台。对于旧版本的MATLAB,您可以使用this other answer中的技巧来完成。