Cast Chars To Int in Template Function

☆樱花仙子☆ 提交于 2019-12-11 23:20:38

问题


I have a C++ template function which prints numbers.

It works fine for everything, except when I'm working with data of type char.

I'd like char to be printed as int, but if I cast this explicitly in the template function, then I will lose precision on my float types.

I'd like to be able to say:

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

But I'm not sure how to do this, or if it is possible.

Any thoughts?


回答1:


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



回答2:


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

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

For more please read here http://www.cplusplus.com/doc/tutorial/templates/ (Template specialization)

Hope it helps



来源:https://stackoverflow.com/questions/9764295/cast-chars-to-int-in-template-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!