私人模板功能 [英] private template functions

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

问题描述

我有一个课程:



Ch

  {
private:
template< int i>
void Func();

//很多其他函数
};

C.cpp

  //很多其他函数

template< int i>
void C :: Func(){
//实现
}

//很多其他函数

我知道,在cpp文件中移动模板实现并不是最好的主意(因为它不会从其他cpp文件中看到,具有模板声明的头)。



但是私有函数呢?

解决方案

当一个函数模板是一个函数模板时,用于触发其实例化的方式,编译器(在某种程度上)需要看到该模板的定义。这是为什么,模板通常使用内联函数在头文件中实现。



因此,只要上面的规则被遵循,仍然可以有接口和






参考:

C ++ 03标准,第14.7.2.4节:

非导出的成员函数模板或类模板的非导出成员函数或静态数据成员应在其显式实例化的每个翻译单元中存在。



I have a class:

C.h

class C {
private:
  template<int i>
  void Func();

  // a lot of other functions
};

C.cpp

// a lot of other functions

template<int i>
void C::Func() {
 // the implementation
}

// a lot of other functions

I know, that it's not the best idea to move template implementation in cpp file (because it won't be seen from other cpp's, which could include the header with the template declaration).

But what about private functions? Could anyone tell me if there are cons of implementing of private template functions in a .cpp file?

解决方案

When a function template is used in a way that triggers its instantiation, a compiler(at some point) needs to see that template's definition. And that is the reason, templates are usually implemented inside a header file using inline finctions.

So as long as the above rules gets followed it is still okay to have interface and implementation separated in header and source files.


Reference:
C++03 standard, § 14.7.2.4:

The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.

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

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