C-的内联重载运算符如何改写为长尾词?
- 内容介绍
- 文章标签
- 相关推荐
本文共计435个文字,预计阅读时间需要2分钟。
我重新加载了运算符用于矩阵输出。代码如下:
cppstd::ostream& operator<<(std::ostream& os, const Tic& b) { for (int i=0; i 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;
}
另外,我创建了一个小型打印功能. 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?
inline void print_matrix (const Matrix& _obj) { cout << _obj; }
也导致调用<<由编译器内联. 问题是:你的前提是错误的.很久以前就引入了inline来控制编译器内联的函数.然而,随着时间的推移,事实证明编译器在决定内联比人类更好的方面要好得多.因此,内联只是对编译器的一个暗示,它的唯一实际用例仍然是告诉链接器,当你在头文件中定义的函数使用内联时,它会找到函数的多个定义.有关详细信息,另请参见here.
TL; DR:上面的内联函数甚至没有告诉你print_matrix是否内联.如果你想知道编译器真正内联的内容,我建议你使用这个工具:godbolt.org/
本文共计435个文字,预计阅读时间需要2分钟。
我重新加载了运算符用于矩阵输出。代码如下:
cppstd::ostream& operator<<(std::ostream& os, const Tic& b) { for (int i=0; i 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;
}
另外,我创建了一个小型打印功能. 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?
inline void print_matrix (const Matrix& _obj) { cout << _obj; }
也导致调用<<由编译器内联. 问题是:你的前提是错误的.很久以前就引入了inline来控制编译器内联的函数.然而,随着时间的推移,事实证明编译器在决定内联比人类更好的方面要好得多.因此,内联只是对编译器的一个暗示,它的唯一实际用例仍然是告诉链接器,当你在头文件中定义的函数使用内联时,它会找到函数的多个定义.有关详细信息,另请参见here.
TL; DR:上面的内联函数甚至没有告诉你print_matrix是否内联.如果你想知道编译器真正内联的内容,我建议你使用这个工具:godbolt.org/

