开发者

template class with static data member used across DLL/SO

Suppose I have such a template class:

template <cl开发者_开发知识库ass T>
class Queue
{
public:
    static int Size;
};

template <class T> int Queue<T>::Size = 0;

And I export a function in D.dll use Queue as an parameter:

void ChangeQueueSize(Queue<int>& q)
{
    q.Size = 100;
}

And then I use this exported function in an A.exe:

Queue<int> q;

q.Size = 10; 

ChangeQueueSize(q);

int updatedSize = q.Size;

Since the Queue class is generated from the class template in 2 projects, there are actually 2 copies of the code, as well as the static data member.

So calling ChangeQueueSize won't really change queue size here, it just update another class's static member, which happens to be have the same class name.

What can we do to solve this problem?

Is weak symbol in gcc capable of address this?

Thanks so much.


You cannot put templates in a library in the way you might think. You can only put actual, instantiated class definitions in a library.

Templates are essentially a code generation tool, and you can only put generated code into the library.

You might want to use explicit template instantiation to make the compiler generate the code, and take the static member definition out of the header:

// Header, shipped to clients
template <class T>
class Queue
{
public:
    static int Size;
};

// Library source code:
template <typename T> int Queue<T>::size = 0;

template class Queue<int>;

Now compile the source file into the library; this will contain the instance of the static member variable Queue<int>::size.

Note that your consumers will only be able to use instances of your class with T = int since they don't have access to the static member otherwise (i.e. they'd have to provide their own).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜