3

I overloaded operator << for matrix output.

std::ostream& operator << (std::ostream& os, const Tic& b)
{
    for (int i = 0; i < b.rows; i++)
    {
        for (int j = 0; j < b.cols; j++)
            os << std::setw(5) << b.board[i][j] << " ";
        os << '\n';
    }
    return os;
}

Also, I created a small function for printing.

inline void print_matrix (const Matrix& _obj)
{
    cout << _obj;
}

Can I use inline for print_matrix function?

Will inline be used for overloaded operator, or does the compiler apply this only for cout and only then will call << as another function?

2 Answers2

4

The effects of inline is mostly to allow things to be included in several files without creating duplicates. The compiler is required to handle this without causing link errors.

Whether a function is actually inlined or not is controlled by compiler options, not by the presence of inline.

Note that the options go all the way from "don't inline anything, even if inline" to "inline whatever seems worthwhile, even if not marked inline".


So, you should mark you function inline if it is in a header file (and that header might possibly be included in more than one source file).

And the same goes for operators, which are a kind of functions with a funny syntax.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
2

If I understand your question correctly, you want to know if the inline in

inline void print_matrix (const Matrix& _obj)
{
    cout << _obj;
}

also causes the call to << be inlined by the compiler.

The thing is: Your premise is wrong. inline was introduced long time ago to control what functions are inlined by the compiler. However, over time it turned out that the compiler is much better at deciding what to inline than humans. As a consequence inline became merely a hint to the compiler and its only pratical use case remains to tell the linker that it will find multiple definitions of the function when you use inline on a function defined in a header. See also here for more details.

TL;DR: The inline above alone does not even tell you whether print_matrix gets inlined or not. If you want to know what the compiler really does inline I recommend you this tool: https://godbolt.org/

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185