开发者

private template functions

I have a class:

C.h

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

  // a lot of other funct开发者_运维知识库ions
};

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.


Unless your private member function template is used by member functions that are defined inline within the class definition, I see nothing wrong with this approach. On the contrary, I think that the less dependencies creep into your header files, the better.

This will work as long as you enforce the convention of always providing each class's implementation in a single source file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜