我想用C++模板创建一个简单的整数范围检查器和转换器。
的代码看起来是这样的:C++中的安全整数转换
// D is the "destination" type and S the "source" type
template <class D, class S>
inline D SafeConvert(S value);
template <class S>
inline int SafeConvert<int>(S value) {
ASSERT(value >= S(INT_MIN) && value <= S(INT_MAX));
return int(value);
} /// error C2768: 'SafeConvert' : illegal use of explicit template arguments
template <class S>
inline size_t SafeConvert<size_t>(S value) {
ASSERT(value >= S(0) && value <= S(size_t(-1)));
return size_t(value);
} /// error C2768: 'SafeConvert' : illegal use of explicit template arguments
// ...
void test() {
size_t v = INT_MAX+1;
int iv = SafeConvert<int>(v);
}
不过,我有以下来编译错误:
error C2768: 'SafeConvert' : illegal use of explicit template arguments
我的问题是如何告诉我要专注只有d类的编译器?
谢谢。
你可能想尝试http://stackoverflow.com/questions/998571/c-template-for-safe-integer-casts/998982#998982 – 2010-06-26 15:17:46