问题
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