如果它们包含在多个cpp
文件中,那我是否需要使用inline
模板函数呢?谢谢。
template<bool> inline QString GetText();
template<> inline QString GetText<true>() {return "true";}
template<> inline QString GetText<false>() {return "false";}
如果它们包含在多个cpp
文件中,那我是否需要使用inline
模板函数呢?谢谢。
template<bool> inline QString GetText();
template<> inline QString GetText<true>() {return "true";}
template<> inline QString GetText<false>() {return "false";}
你需要这么做,因为它们是完整的功能专业化程序,因此与普通函数一样受到一个定义规则的约束。
inline
关键字。这样可以吗?比如 template<bool> QString GetText();
- user1899020是的,你需要在那里使用 inline
指定符。
ODR(一次定义规则)规定变量、函数、类、枚举或模板必须有且仅有一个定义。与您问题相关的异常列在 §3.2/5(C++11)中(强调我的):
程序中可以有多个类类型(第9条)、枚举类型(7.2)、具有外部链接的内联函数(7.1.2)、类模板(第14条)、非静态函数模板(14.5.6)、类模板的静态数据成员(14.5.1.3)、类模板的成员函数(14.5.1.1)或者未指定某些模板参数的模板特化(14.7、14.5.5),只要每个定义出现在不同的翻译单元中,并且提供的定义满足以下要求。[...]
在其中未列出明确指定了所有参数(即显式特化)的模板特化,§14.7.3/12说:
An explicit specialization of a function template is inline only if it is declared with the inline specifier or defined as deleted, and independently of whether its function template is inline. [ Example:
template<class T> void f(T) { /∗ ... ∗/ } template<class T> inline T g(T) { /∗ ... ∗/ } template<> inline void f<>(int) { /∗ ... ∗/ } // OK: inline template<> int g<>(int) { /∗ ... ∗/ } // OK: not inline
— end example ]
template<> int g<>(int) { /∗ ... ∗/ }
需要关键字 inline
。 - user1899020===============
根据Jesse Good的评论更新答案(需要模板全特化内联)。感谢Jesse Good指出这一点。
inline
关键字。这些是模板的 特化,如果包含在多个源文件中将会违反 ODR。 - Jesse Good[temp.expl.spec]/12
,"函数模板的显式特化仅在使用内联说明符声明或定义为已删除时才是内联的,而不管其函数模板是否内联。" - Mankarse看起来模板方法必须在构建的同一文件中定义,您不需要使用“inline”关键字,因为它们已经在包含它的每个cpp文件中构建。
inline
模板函数中获得什么? - Oswald