alexlesh
alexlesh

Reputation: 21

dllexport'ing a static template method

I am trying to create a templated factory class that exports a create method:

template <typename T>
class ClassFactory
{
    _declspec(dllexport) static void* Create()
    {
        return new T;
    }
};

class Foobar : ClassFactory<Foobar>
{
    std::string foo;
};

This code compiles just fine, but I don't see anything in the exports table when I look at the output of dumpbin /exports

The following code exports Create() correctly:

class ClassFactoryBase
{
    _declspec(dllexport) virtual void* Create() = 0;
};

template <typename T>
class ClassFactory : ClassFactoryBase
{
    void* Create()
    {
        return new T;
    }
};

class Foobar : ClassFactory<Foobar>
{
    std::string foo;
};

However, I need Create() to be static. Why does sample 2 work, while sample 1 does not? Is there a way to export a static template method?

Upvotes: 2

Views: 1364

Answers (2)

Gart
Gart

Reputation: 2336

The compiler sees that the Create() function is never called so it does not generate any code for it. To make it work you need to explicitly instantiate your template like this:

template class ClassFactory<Foobar>;

Just add this line to your source. Now the compiler will generate the code for this function and export it. For more information see this MSDN article - Explicit Instantiation (C++)

To answer your other question why the example 2 works and example 1 does not, let's take a closer look at the derived class Foobar. There is a virtual function in this class so the compiler has to generate a vtable. To fill in the vtable the compiler needs to know the address of Create() and this is when it is implicitly instantiated from the base class template. The code for this function is generated and exported to the DLL, as requested. That is why the example 2 works.

Upvotes: 3

Spook
Spook

Reputation: 25927

There is no way to export a template method from the DLL, because non-instanced template method is not even compiled. Your examples doesn't do much with the DLL itself, the header file is the one, who makes everything work.

Upvotes: 0

Related Questions