所有代码从我读过的内容来看,A1和A2是相同的,但如果A3与A2完全相同,我不会这么做。 我知道代码将被编译,因为所有的A类都被模板化了。
注意:所有的类和方法声明都在.h文件中。
template <typename _Ty> class A1 { public: A1(); void foo() { ... } }; template <typename _Ty> class A2 { public: A2(); void foo(); }; template <typename _Ty> inline void A2<_Ty>::foo() { ... } template <typename _Ty> class A3 { public: A3(); void foo(); }; template <typename _Ty> void A3<_Ty>::foo() { ... } // note: No inline keyword here.PS我已经看到了这个问题的变种在stackoverflow,但不是这个确切的问题。
All code From what I've read, A1 & A2 are identical, but I don't if A3 is identical to A2. I know the code will compile since all of the A classes are tmemplated.
Note: All of the class & method declarations are in a .h file.
template <typename _Ty> class A1 { public: A1(); void foo() { ... } }; template <typename _Ty> class A2 { public: A2(); void foo(); }; template <typename _Ty> inline void A2<_Ty>::foo() { ... } template <typename _Ty> class A3 { public: A3(); void foo(); }; template <typename _Ty> void A3<_Ty>::foo() { ... } // note: No inline keyword here.P.S. I've seen variants of this question on stackoverflow, but not this exact question.
最满意答案
是的,这是有意义的,但与模板结合时效果不佳。
inline关键字的主要作用是告诉编译器该函数可能在多个编译单元中以相同的定义出现,所以它需要被标记为链接器的“选择一个”(所以你不会得到多重定义错误)。 模板已具有此功能。
inline还向编译器提示您认为该函数应该内联,但编译器通常会自行对内联优化做出最终决定。
Yes, it's meaningful, but doesn't have much effect when combined with templates.
The major effect of the inline keyword is to tell the compiler that this function may appear with the same definition in multiple compilation units, so it needs to be flagged as "select-one" for the linker (so you don't get multiple definition errors). Templates already have this feature.
inline also is a hint to the compiler that you think the function should be inlined, but the compiler usually makes the final decision on inlining optimizations on its own.
更多推荐
发布评论