Export derived class with template base class and template argument is derived itself
Asked Answered
M

0

9

I have a quick question in the hope someone knows if what I'm trying is possible at all.

Assume I have a template base class like this

template <class T> 
class CBase
{
    public: 
        CBase() {}
        void print() { std::cout << n std::endl; }
    private:
    T m_var;
};

And want a derived class which derives from CBase using itself as the templates argument:

class CDerived : public CBase<CDerived>
{
    public: 
        CDerived () {}
};

I have a library which is structured a lot in that way and so far this library was build static and everything is fine. But now I want to change it to a dynamic library, therefore I added the export/import keyword for the derived class:

#if defined(BUILD_LIBRARY)
#  define EXPORT __declspec(dllexport)
#else
#  define EXPORT __declspec(dllimport)
#endif

class EXPORT CDerived : public CBase<CDerived>
{
    public: 
        CDerived () {}
};

This builds and links fine, but as soon as I use CDerived in a executable, I get linker errors about CBase. References to any of the CBase methods or constructors are not found.

I've read a lot about exporting the template specialization, but in this did not help. It seems that this scenario is in general solvable but since my derived class is also the template argument there might be a problem.

Can someone tell me if this special case can be exported or is it just not possible at all?

Molality answered 24/4, 2014 at 11:51 Comment(7)
Have you included your CDerived header (in a translation unit) when building the library?Emblazonry
There is a solution for this at another StackOverflow postDetwiler
I did include it yes. I'm aware of the general solutions to export template subclasses but this is a special case also described here msdn.microsoft.com/en-us/library/twa2aw10%28v=vs.100%29.aspx (last section). However, I don't really get from the text if its possible or not finallyMolality
Seems, you left CBase definition without implementation in a header. Template classes must be implemented right in a header file.Unrestrained
Try to use only .H fileTrapeziform
I am not seeing the linker error that you are seeing. I tested it in Visual Studio 2008.Detwiler
It was indeed my fault, the base class was not header only. No idea how I could miss that :(Molality

© 2022 - 2024 — McMap. All rights reserved.