过载运算符<<对于数组

时间:2012-02-23 21:23:32

标签: c++ operator-overloading iostream

我想为任意数组重载operator<<,这样代码cout << my_arr就可以了。首先,我尝试在operator<<上重载const T (&arr)[N]的第二个参数,其中TN是模板参数。但是测试代码会发现副作用: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 */
}

这样的阵列打印操作员是否仍然可以实现?

1 个答案:

答案 0 :(得分:5)

不确定

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])
{
    // ...
}

这会在使用SFINAE Tchar时禁用您的过载。

对于C ++ 03,Boost有enable_ifis_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; 
};
相关问题