更新时间:2023-12-01 17:20:22
一个类型和两个常见的已知***拟合类型,但您的模板运算符<
Your template has three arguments, a type, and two constants of a known best fit type, but your templated operator<<
takes an instantiation of the template with three types.
template<class Int_T = int, typename Best_Fit<Int_T>::type Min_Range
= std::numeric_limits<Int_T>::min(), // constant!
typename Best_Fit<Int_T>::type Max_Range
= std::numeric_limits<Int_T>::max() // constant!
>
class Int
//...
template<class Int_T>
std::ostream& operator<<(std::ostream& out,
const Int<Int_T,
Best_Fit<Int_T>::type, // type!
Best_Fit<Int_T>::type // type!
>& obj)
我通常建议类模板在类定义中定义(使用 friend
在该上下文中定义一个***函数)因为这个特殊的原因,在类模板中获取类型是很容易的,容易在其外失效。还有一些其他的差异(像事实,如果运算符被定义在类中,那么它只能通过ADL访问 - 无论你也决定在外部声明)
I usually recommend that operator overloads of class templates are defined inside the class definition (use friend
to define a free function in that context) for this particular reason, it is trivial to get the types right inside the class template, and easy to fail outside of it. There are a couple other differences (like the fact that if the operator is defined inside the class then it will only be accessible through ADL --unless you also decide to declare it outside)
template<class Int_T = int, typename Best_Fit<Int_T>::type Min_Range
= std::numeric_limits<Int_T>::min(), // constant!
typename Best_Fit<Int_T>::type Max_Range
= std::numeric_limits<Int_T>::max() // constant!
>
class Int {
friend // allows you to define a free function inside the class
std::ostream& operator<<( std::ostream& out,
Int const & obj ) { // Can use plain Int to refer to this
// intantiation. No need to redeclare
// all template arguments
return out << obj.get_data();
}
};