类体外的模板定义 [英] Template definitions outside class body

查看:117
本文介绍了类体外的模板定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是吗?定义类模板的虚函数在其体外?虚函数不能被内联,但是为了避免编译单元中的多个定义,它们应该标记为 inline (假设模板头将被包括在多个源文件中)。另一方面,编译器可以忽略 inline ,所以这似乎有效。例如,下面的代码是正确的:

  template< typename T> 
class C
{
public:
virtual void f(T val);
};

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



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

解决方案

是的,即使没有 inline 。它对于普通成员函数和静态变量是相同的:

  //头部中的一切:
template<类T>
class A
{
static int i;
};

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

标准报价:(3.2 / 5)



< blockquote>

可以有一个类类型的多个定义(第9条),枚举类型(7.2),内联函数
外部链接(7.1.2),类模板14),非静态函数模板(14.5.6),类模板(14.5.1.3)的静态数据成员
,类模板的成员函数(14.5.1.1)或
的模板专用化,其中在程序中没有指定一些模板参数(14.7,14.5.5),条件是每个定义
出现在不同的翻译单元中,并且条件满足以下要求。


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



它不工作在常规类的情况下。整个程序中最多只能有一个定义。


Is it O.K. to define virtual function of class template outside its body? Virtual function can not be inlined, but to avoid multiple definitions in compilation units they shall be marked inline (assuming that template headers will be included in multiple source files). On the other hand compiler is free to ignore inline, so this seems valid. By an example, is the code below correct:

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) allows to omit inline before definition of function f(T val) but not before analogous function of regular class. Is it only gcc's behaviour?

解决方案

Yes, it's OK even without inline. It works the same for ordinary member functions and static variables:

// everything in the header:
template <class T>
class A
{
  static int i;
};

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

Standard quote: (3.2/5)

There can be more than one definition 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 specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements ...

The requirements basically say the two definitions have to be identical.

It doesn't work in case of regular classes. There has to be at most one definition in the whole program.

这篇关于类体外的模板定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆