微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 私人模板功能

我有一个班:

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

我知道,在cpp文件中移动模板实现并不是最好的办法(因为它不会从其他cpp看到,可能包括带有模板声明的头文件).

但私人功能呢?有没有人可以告诉我,在.cpp文件中是否存在实现私有模板功能的缺点?

解决方法

当以触发其实例化的方式使用函数模板时,编译器(在某些时候)需要看到该模板的定义.这就是原因,模板通常使用内联功能在头文件中实现.

所以只要遵守上述规则,仍然可以在头文件和源文件中分离接口和实现.

参考:
C 03标准,§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.

原文地址:https://www.jb51.cc/c/113059.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐