简体   繁体   中英

Where to define class with both template and non-template members?

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.

  • But if I chuck all the implementation in the header, I'll end up multiply defining baz .
  • 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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM