缺少运算符<<但它就在那里

时间:2011-10-17 07:20:56

标签: c++ templates

在此类中运算符<<在尝试使用gcc 4.6.1编译它时定义(参见代码)我得到跟随错误:'operator<<'不匹配在'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;
}

1 个答案:

答案 0 :(得分:2)

您的模板有三个参数,一个类型,以及一个已知最适合类型的两个常量,但您的模板化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();
   }
};