C++模板和内联
当我编写一个简单(非模板)类时,如果函数实现“就地”提供,它会自动被视为内联
。
class A {
void InlinedFunction() { int a = 0; }
// ^^^^ the same as 'inline void InlinedFunction'
}
当谈论基于模板的类时,这条规则怎么样?
template <typename T> class B {
void DontKnowFunction() { T a = 0; }
// Will this function be treated as inline when the compiler
// instantiates the template?
};
另外,内联规则如何应用于非嵌套模板函数,例如
template <typename T> void B::DontKnowFunction() { T a = 0; }
template <typename T> inline void B::DontKnowFunction() { T a = 0; }
第一种情况和第二种情况会发生什么?
谢谢。
When I'm writing a simple (non-template) class, if the function implementation is provided "right in place", it's automatically treated as inline
.
class A {
void InlinedFunction() { int a = 0; }
// ^^^^ the same as 'inline void InlinedFunction'
}
What about this rule when talking about template-based classes?
template <typename T> class B {
void DontKnowFunction() { T a = 0; }
// Will this function be treated as inline when the compiler
// instantiates the template?
};
Also, how is the inline
rule applied to non-nested template functions, like
template <typename T> void B::DontKnowFunction() { T a = 0; }
template <typename T> inline void B::DontKnowFunction() { T a = 0; }
What would happen in the first and in the second case here?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为当你实例化你得到一个类时,该函数就像一个普通的成员函数。它是在该类中定义的,因此该函数会自动内联。
但在这里这并不那么重要。无论如何,您可以在程序中多次定义函数模板或类模板的成员 - 您不需要像在非模板情况下那样通过内联来告诉编译器这一点。
Since when you instantiate you get a class, that function is like an ordinary member function. It's defined in that class, so the function is automatically inline.
But it does not really matter here that much. You can define function templates or members of class templates multiple times in a program anyway - you don't need
inline
to tell the compiler about that like in the non-template case.inline 关键字不是“规则”。它只是对编译器的建议/提示,它的作用完全取决于它及其实现。考虑到这一点,不可能知道您的示例会发生什么。事实上,编译器可能内联所有、部分或不内联它们。
The inline keyword is not a "rule". It is merely a suggestion/hint to the compiler and what it does with it is completely up to it and it's implementation. With this in mind, it's not possible to know what will happen with your examples. The compiler may in fact inline all, some, or none of them.
据我所知,模板化函数是自动内联的。然而,现实情况是大多数现代编译器经常忽略内联限定符。编译器的优化启发式很可能比人类程序员在选择内联函数方面做得更好。
Templated functions as far as I know are automatically inline. However, the reality is that most modern compilers regularly ignore the inline qualifier. The compiler's optimizing heuristics will most likely do a far better job of choosing which functions to inline than a human programmer.