詮釋這一類,其中運營商< <定義(見代碼),而試圖用gcc 4.6.1我得到以下錯誤編譯:在沒有比賽的「運營商< <」 'std :: cout < < a'。這是怎麼回事?缺少操作員<<但它的存在
template<class Int_T = int, typename Best_Fit<Int_T>::type Min_Range = std::numeric_limits<Int_T>::min(),
typename Best_Fit<Int_T>::type Max_Range = std::numeric_limits<Int_T>::max()>
class Int
{
Int_T data_;
Int_T get_data()const
{
return data_;
}
};
//Here is this operator defined
template<class Int_T>
std::ostream& operator<<(std::ostream& out, const Int<Int_T, Best_Fit<Int_T>::type, Best_Fit<Int_T>::type>& obj)
{
out << obj.get_data();
return out;
}
其中Best_Fit樣子:
#ifndef BEST_FIT_H_INCLUDED
#define BEST_FIT_H_INCLUDED
struct Signed_Type
{
typedef long long type;
};
struct Unsigned_Type
{
typedef unsigned long long type;
};
template<bool Cond, class First, class Second>
struct if_
{
typedef typename First::type type;
};
template<class First, class Second>
struct if_<false,First,Second>
{
typedef typename Second::type type;
};
template<class Int_T>
struct Best_Fit
{//evaluate it lazily ;)
typedef typename if_<std::is_signed<Int_T>::value,Signed_Type,Unsigned_Type>::type type;
};
#endif // BEST_FIT_H_INCLUDED
編輯:
#include <iostream>
int main(int argc, char* argv[])
{
Int<signed char,1,20> a(30);
cout << a;
}
可以爲用戶提供一個例子主要? –
@VJo編輯,見OP – smallB
這是一些快樂的模板魔法。你在包裝標準的數字類型,不是嗎?如果不是祕密,你的目標是什麼?你爲什麼做這個? – Septagram