How to overload operator

1 day ago 1
ARTICLE AD BOX

I am trying to overload operator<< for a C-style array passed by reference to a function, like this:

#include <cstdint> #include <iostream> #include <algorithm> #include <iomanip> #include <string> template<typename T, size_t N> inline std::ostream &operator<<(std::ostream& os, const T (&array)[N]) { os << std::hex; for (const auto &byte : array) os << std::string("0x") << std::setw(2) << std::setfill('0') << (int)byte << std::string(" "); os << std::dec; return os; } template<typename T, size_t N> void print_array(const T (&array)[N]) { std::cout << array << std::endl; // ambiguous overload for operator<< } int main(int, char *argc[]) { uint8_t array[10] = {0}; std::cout << array << std::endl; // OK print_array(array); // does not compile return 0; }

The compilation error is:

<source>:22:15: error: ambiguous overload for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'const unsigned char [10]') 22 | std::cout << array << std::endl; // ambiguous overload for operator<< | ~~~~~~~~~~^~~~~~~~ <source>:22:15: note: there are 42 candidates .... (more)

However, overloaded operator<< works as expected when called directly.

I guess the problem comes from print_array() using a parameter which is a reference to an array, and then calling the overloaded operator<< with this reference inside of the function.

How to fix this?

Remy Lebeau's user avatar

Remy Lebeau

611k36 gold badges520 silver badges876 bronze badges

vazlsky's user avatar

13

Read Entire Article