-
problem with templates
i have code:
Code:
//main.cpp
#include "src/shm_obj.h"
struct __DATA{
int index;
char *value[200];
};
typedef __DATA data;
int main(int argc,char **argv){
data *d=new data;
d->index=123;
strcpy((char*)d->value,"qwerty");
shm_obj<data>::create(d); //!!! undefined reference to 'shm_obj<__DATA>::create(__DATA*)'
return EXIT_SUCCESS;
}
Code:
//shm_obj.h
#ifndef SHM_OBJ_H_
#define SHM_OBJ_H_
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
template<typename T>
class shm_obj{
private:
T *obj;
static shm_obj<T> *__instance;
private:
shm_obj(T *__obj);
public:
static shm_obj<T> create(T*);
static T *get();
virtual ~shm_obj();
};
#endif /*SHM_OBJ_H_*/
Code:
//shm_obj.cpp
#include "shm_obj.h"
template<typename T>
shm_obj<T>::shm_obj(T *__obj){
this->obj=__obj;
}
template<typename T>
shm_obj<T> shm_obj<T>::create(T *__obj){
shm_obj<T>::__instance=new shm_obj<T>;
return shm_obj<T>::__instance;
}
template<typename T>
T *shm_obj<T>::get(){
return __instance->obj;
}
template<typename T>
shm_obj<T>::~shm_obj(){
}
where is error??
help me please...
-
Generally, to use templates, the compiler needs to see the definition of the template functions. In other words, the compiler, when compiling your main.cpp, needs to see the content of shm_obj.cpp. This is one of the cases where you might want to actually #include a .cpp file, rather than compiling it separately.
There are exceptions to this (depending on your compiler) but I'll bet your compiler isn't one of the exceptions.
There is also a problem that names beginning with an underscore are reserved for use by the implementation (i.e. the compiler and library) in some way. In other words, you shouldn't name anything as __DATA. [Specifically, if you're not afraid of the details, names with two leading underscores or one underscore and an uppercase letter are reserved to the implementation. Other names beginning with an underscore are reserved for the implementation as a name in the global namespace.]
-
thanks to grumpy
i consistent that what
-
Valery, my compiler tells me you are calling a default constructor with
shm_obj<T>::__instance=new shm_obj<T>;
but you have no such constructor.
Did you mean to write:
shm_obj<T>::__instance=new shm_obj<T>(__obj);
Also, the create method should return shm_obj<T>*
I hope that helps.
-
Quote:
Code:
strcpy((char*)d->value,"qwerty");
Nothing to do with templates, but that's wrong. value is an array of pointers to char. You must not copy a string there. Yes, you've put a cast there presumably to get rid of the warning the compiler is screaming at you, but that's like ripping the label off a can of rat poison and sticking on a new label that says "delicious anchovies"
-
I'd advise you use std::string instead of char* and you had better have a really good reason to cast something in C++. I do not consider this is one of those things.
Besides that, you never delete what you new.