如何判断 c++ 向量中的值类型(整数或双精度)?
How to judge a value type (int or double) in c++ vector?
我正在使用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
}
}
我可能需要对我的if
和else
做出判断。或者对其他解决方案有任何建议?
从 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,您可以使用另一个答案中的技巧来执行此操作。
相关文章:
- 整数类型应该显式转换(例如"int"到"无符号")还是只会增加混乱?
- 涉及旧式枚举和整数类型的重载解析
- 将字符串转换为整数类型T,检查是否存在溢出
- 整数文本太大,无法用任何整数类型表示--C++
- isdigit(c) - 字符或整数类型?
- 为什么对小于 4 个字节的整数类型的位操作会发生意外行为?
- C++模板专用化 - 将其他整数类型委托给uint64_t
- 何时应使用 C++ 固定宽度整数类型,它们如何影响性能?
- 根据浮点数选择最小整数类型
- 为什么 QVariant 将字符类型视为整数类型
- 我们可以在整数类型的双指针中分配2D整数数组的地址吗?怎么可能
- 默认情况下,决定整数类型是唱歌或无符号的类型
- 是否可以根据类型是整数类型还是浮点类型重载模板函数
- 使用固定整数类型的安全性
- 如何使用条件来检查类型名 T 是否是 C++ 中浮点类型的整数类型
- C++文本整数类型
- 哪种整数类型可以安全且便携式用于始终保持指针值
- 检测整数类型变量上的空白输入
- 为什么对Chrono :: Nanseconds的表示类型是签名的整数类型
- 如何处理警告:从较小的整数类型int转换为int*