重载算子<<对于数组
我想为任意数组重载operator<<
,以使代码cout << my_arr
可以工作。首先,我尝试在const T (&arr)[N]
上过载operator<<
的第二个参数,其中T
和N
是模板参数。但测试代码揭示了一个副作用:const char[]
也匹配类型规范,并且新的过载与流类中定义的过载冲突。示例代码:重载算子<<对于数组
#include <cstddef>
#include <iostream>
template<typename T, std::size_t N>
std::ostream& operator<<(std::ostream& os, const T (&arr)[N])
{
/* do stuff */
return os;
}
int main()
{
std::cout << "noooo\n"; /* Fails: ambiguous overload */
}
这样的数组打印操作符仍可以实现吗?
肯定的:
template<typename T, std::size_t N>
typename std::enable_if<!std::is_same<T, char>::value, std::ostream&>::type
operator<<(std::ostream& os, const T (&arr)[N])
{
// ...
}
这将禁用过载时T
是char
使用SFINAE。
对于C++ 03,Boost有enable_if
和is_same
。或者只是推出自己的:
template<class T, class U> struct is_same {
enum { value = false };
};
template<class T> struct is_same<T, T> {
enum { value = true };
};
template<bool, class T> struct enable_if {};
template<class T> struct enable_if<true, T> {
typedef T type;
};
任何C++ 03解决方案? – 2012-02-23 21:36:41
@ Mr.Anubis:改用'boost :: enable_if'和'boost :: is_same'。如果你不想要Boost,你自己实现它们,这两个都是微不足道的。 – 2012-02-23 21:38:00
@GeorgFritzsche:你说得对。但是,它应该是?我猜''const T(&)[]'也可以绑定到一个非const数组,所以是的,写得很好。它的深层次的'const'不能隐式添加。 – 2012-02-23 22:25:47
我不认为N会在很多情况下良好传输。 'void f(int arr [],size_t N){cout 2012-02-23 21:31:32
如果你想要一个外部库,为什么不使用http://www.boost.org/doc/libs/1_48_0/doc/html/boost_lexical_cast.html – pyCthon 2012-02-23 21:33:33
@Captain:'arr'实际上有'int * '在这种情况下,所以它不会匹配那个过载。 – 2012-02-23 21:49:51