c语言中函数的标头,C-在模板类之外但在标头中定义成员函数

14.7 / 5说

5 For a given template and a given set of template-arguments,

an explicit instantiation definition shall appear at most once in a program,

an explicit specialization shall be defined at most once in a program (according to 3.2), and

both an explicit instantiation and a declaration of an explicit specialization shall not appear in a program unless the explicit

instantiation follows a declaration of the explicit specialization.

An

implementation is not required to diagnose a violation of this rule.

第二点适用于您的情况. 3.2中定义的ODR可以说相同的内容,尽管形式较少.

无论在何处以及如何定义成员函数的非专业版本,专业版本定义

template <> bool TestClass::MemberFunction()

{

return true;

};

必须进入一个.cpp文件.如果保留在头文件中,则一旦将头包含到多个翻译单元中,它将产生违反ODR的行为. GCC可以可靠地检测到这种违规行为. MSVC在这方面似乎不太可靠.但是,正如上面的引用所述,不需要执行即可诊断是否违反了此规则.

头文件应仅包含该专业化的未定义声明

template <> bool TestClass::MemberFunction();

在MSVC中错误的出现或消失的事实取决于看似无关的因素,例如如何定义函数的非专业版本,这必须是MSVC编译器的怪癖.

经过进一步的研究,似乎MSVC实现实际上已被破坏:其行为超出了语言规范所提供的“无需诊断”许可所允许的范围.

您在实验中观察到的行为与以下行为一致:将主要功能模板声明为内联会自动使该模板的显式特化也内联.事实并非如此.在14.7.3 / 14中,语言规范规定

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值