在尝试使用 gcc 4.6.1 编译它时,在定义了 operator<< 的这个类中(参见代码)我得到以下 error: no match for 'operator<<' in 'std::cout <<一个'。这是怎么回事?
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;
}
最佳答案
您的模板具有三个参数、一个类型和两个已知最适合 类型的常量,但您的模板化 operator<<
使用三种类型的模板实例化。
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 访问——除非您还决定在外部声明它)
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();
}
};
关于c++ - 缺少运算符 << 但它在那里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7790524/