限定类的<<操作符(函数模板)输入的为整数类型
需要实现如下功能:
class A
{
public:
template <typename T>
A & operator<<(T rhs)
{
//some integral operation
}
};
int main(void)
{
A a;
a << 123; //Ok
a << 123.0/*或其他非整数类型*/; //编译失败,且错误信息指向本行
}
已经考虑过的方法如下:
1. 如果是想对类模板的参数限制类型,可以如下:
template <typename T, typename Enable = void>
class A;
template <typename T>
class A <T, typename boost::enable_if<boost::is_integral<T>>::type>
{
//
};
但函数模板无法偏特化,也不能指定默认模板参数。
2.如果普通函数,可以如下:
template <typename T>
std::auto_ptr<char> itoa(T value, int base, typename boost::enable_if<boost::is_integral<T>>::type * = 0)
{
//some integral operation
}
但operator<<不能提供额外的函数参数。
3.或者对于参数无法增加的函数,可以如下:
template<typename T>
typename boost::enable_if<boost::is_integral<T>>::type
itoa(T value, char * str, int base)
{
//some integral operation
}
但为了能够连续输入,形如:a << 123 << 456 << 789等,operator<<的返回值又必须为A &。
4. 参考VC的stl basic_ostream实现源码:
basic_ostreamt& operator<<(unsigned short _Val);
basic_ostream& operator<<(int _Val);
basic_ostream& operator<<(unsigned int _Val);
.....等等其他整数类型的重载函数(oh, my god)
......别扭
诸位大侠有没有高招?