private template functions

2019-04-18 07:10发布

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?

2条回答
The star\"
2楼-- · 2019-04-18 07:50

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.

查看更多
贼婆χ
3楼-- · 2019-04-18 08:00

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.

查看更多
登录 后发表回答