加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 班级外的模板定义

发布时间:2020-12-16 05:43:33 所属栏目:百科 来源:网络整理
导读:是吗在其身体之外定义类模板的虚拟功能?虚拟函数不能内联,但为避免编译单元中的多个定义,它们将被内联标记(假设模板头将包含在多个源文件中).另一方面,编译器可以自由地忽略内联,所以这似乎是有效的.例如,下面的代码正确: template typename Tclass C{publ
是吗在其身体之外定义类模板的虚拟功能?虚拟函数不能内联,但为避免编译单元中的多个定义,它们将被内联标记(假设模板头将包含在多个源文件中).另一方面,编译器可以自由地忽略内联,所以这似乎是有效的.例如,下面的代码正确:
template <typename T>
class C
{
public:
    virtual void f(T val);
};

template <typename T>
inline
void C<T>::f(T val)
{
  //definition
}

BTW gcc(3.4.2)允许在定义函数f(T val)之前省略内联,但在常规类的类似功能之前不允许内联.这只是gcc的行为吗?

解决方法

是的,即使没有内联也行.它对普通成员函数和静态变量的工作原理相同:
// everything in the header:
template <class T>
class A
{
  static int i;
};

template <class T>
int A<T>::i=0;

标准报价:(3.2 / 5)

There can be more than one de?nition of a class type (Clause 9),enumeration type (7.2),inline function with
external linkage (7.1.2),class template (Clause 14),non-static function template (14.5.6),static data member
of a class template (14.5.1.3),member function of a class template (14.5.1.1),or template specialization for
which some template parameters are not speci?ed (14.7,14.5.5) in a program provided that each de?nition
appears in a di?erent translation unit,and provided the de?nitions satisfy the following requirements …

要求基本上说这两个定义必须相同.

它不适用于常规课程.整个计划中最多只有一个定义.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读