在模板函数中将字符强制转换为Int

Cast Chars To Int in Template Function

本文关键字:转换 Int 字符 函数      更新时间:2023-10-16

我有一个C++模板函数,它可以打印数字。

除了使用char类型的数据外,它适用于所有情况。

我希望char打印为int,但如果我在模板函数中显式强制转换,那么我将失去float类型的精度。

我想说:

template<class T> bob(T a){
  cout<<if_char_make_int(a)<<endl;
}

但我不知道该怎么做,也不知道这是否可能。

有什么想法吗?

template<class T> void bob(T a){
  cout<< a <<endl;
}
template<> void bob(char a){
  cout<< static_cast<int>(a) <<endl;
}

欲了解更多信息,请阅读此处http://www.cplusplus.com/doc/tutorial/templates/(模板专业化)

希望它能帮助

template<class T> void bob(T a){
    std::cout
      << typename boost::mpl::if_<boost::is_same<char, T>, int, T>::type(a)
      << std::endl;
}