C++ 模板和内联
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3694899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ template and inline
提问by Yippie-Ki-Yay
When I'm writing a simple (non-template) class, if the function implementation is provided "right in place", it's automatically treated as inline
.
当我编写一个简单的(非模板)类时,如果函数实现是“就地”提供的,它会自动被视为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
此外,inline
规则如何应用于非嵌套模板函数,例如
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.
谢谢你。
采纳答案by Puppy
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.
据我所知,模板化函数是自动内联的。然而,现实是大多数现代编译器经常忽略内联限定符。与人类程序员相比,编译器的优化启发式很可能在选择要内联的函数方面做得更好。
回答by Johannes Schaub - litb
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
像在非模板情况下那样告诉编译器。
回答by RC.
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.
inline 关键字不是“规则”。它只是对编译器的建议/提示,它用它做什么完全取决于它和它的实现。考虑到这一点,不可能知道您的示例会发生什么。编译器实际上可能会内联所有、部分或不内联它们。