我想用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