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?
Function templates. Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.
You may define a template member function outside of its class template definition. When you call a member function of a class template specialization, the compiler will use the template arguments that you used to generate the class template.
You cannot have a virtual template function because as far as the compiler is concerned they are two completedly different functions; as their implicit this parameter is of different type. Another reasons why virtual templates can't work are equally valid.
A template is a C++ programming feature that permits function and class operations with generic types, which allows functionality with different data types without rewriting entire code blocks for each type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With