C
C
Ckpyt2013-03-21 16:43:09
C++ / C#
Ckpyt, 2013-03-21 16:43:09

Templates in cpp, what and how?

How to separate the implementation of a template from its declaration?
For example:
queue.h:

template<class T> queue{
struct item{
   atomic<T> itm
   item*next
}
queue();
push();
pop();
~queue();
}

queue.cpp
template<typename  T>
queue<T>::queue()
{
  Head=new qq;
  End=Head;
}

template<typename  T>
void queue<T>::push(T* item){
  try{
    Logger("Function::%s position:%s:%i",__FUNCTION__,__FILE__,__LINE__);
    item* t=new item;
    t->item=NULL;
    t->next=NULL;
    End->itm=new atomic<T*>;
    End->itm->store(item);
    End->next=t;
    End=End->next;
  }
  catch(...){
    Exout("Exception::%s position:%s:%i",__FUNCTION__,__FILE__,__LINE__);
    throw;
  }
}
и т.д.

The code in this form, in the place where the template is used, gives a linking error
P.s. why is it necessary: ​​the GUI of the project is written in .NET, and the studio says that it cannot use the CLR and atomic at the same time.
P.p.s: VS 2012, c++2011 standard

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
jcmvbkbc, 2013-03-21
@Ckpyt

If the Ts to be used are known in advance, you can explicitly instantiate the required types in queue.cpp .
For example:

template class queue<int>;

C
Chaos_Optima, 2013-03-21
@Chaos_Optima

#include "queue.cpp"

[
[email protected]><e, 2013-03-21
@barmaley_exe

And what should the compiler compile from the cpp file? What is the object file?
The implementation of template methods / functions cannot be moved to a separate translation unit, follow the advice of Chaos_Optima

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question