Reputation: 10156
I know template definitions should all go into the header file [1]. But what to do if I have both templates and non-templates in a class:
// cls.h
class cls {
public:
template <typename U> void bar(U x); // template
void baz(); // non-template
template <typename V> class nest {
};
};
// foo1.cpp
#include "cls.h" ...
// foo2.cpp
#include "cls.h" ...
Ideally I want to define bar
and baz
in the same file as they are so closely related.
baz
. .cpp
, then definitions for bar
and nest
can't be seen by foo1.cpp
or foo2.cpp
.Do I have to split bar
and baz
between seperate files?
[1] Declaring templates as inline
doesn't seem work for me on MSVC++ using NVCC to compile CUDA code.
Upvotes: 2
Views: 434
Reputation: 126442
But if I chuck all the implementation in the header, I'll end up multiply defining baz.
You can still mark the function definition for baz()
as inline
. That will allow you to put the definition of baz()
in a header file without leading to multiple symbol definition errors.
If I chuck all the implementation into a .cpp, then definitions for bar and nest can't be seen by foo1.cpp or foo2.cpp.
If you know in advance what types your function template is going to be instantiated with, you can use explicit instantiations in the .cpp
files that contain the definitions of your function templates.
template void cls::bar(int);
If none of the above options are OK for you, then you will have to give up this requirement:
Ideally I want to define bar and baz in the same file as they are so closely related.
And put the definition of member function templates in the header file, and the definition of non-template member functions in a .cpp
file.
Upvotes: 5