I have several small classes that are all peers of each other declared and defined in the same file. A lot of these classes share information. Currently, the type of the shared information is hard-coded for initial development and testing purposes, but I want to templatize (verb form?) the classes. However, if I write the template
construct before each class, that creates the possibility that a user could create instances of each class with different type arguments, which will most likely lead to errors in the data or code. Is there a way to force all class instances to be created with the same type?
The only way I can think of doing this is to create an additional init
or spawner
class with members functions like createInstanceOfA()
, createInstanceOfB()
, etc., where the user would have to first create an instance of the spawner
class with the desired type, then use its member functions to create instances of the other classes. Of course, this would mean that my spawner
class would have to stay in sync with whatever utility classes I have (which shouldn't be a problem). However, is there a better way of doing this?
EDIT: As an example, my "ugly solution" (a simple case):
template <typename T>
struct A {
void manipulate( T arg );
};
template <typename T>
struct B {
void manipulate( T arg );
};
template <typename T>
struct C {
void manipulate( T arg );
};
template <typename T>
struct Spawner {
A<T> createInstanceOfA( void );
B<T> createInstanceOfB( void );
C<T> createInstanceOfC( void );
};
int main() {
// don't allow
A<int> a;
B<float> b;
C<double> c;
// allow
Spawner<int> s;
A<int> s.createInstanceOfA(); // not sure if syntax is correct
B<int> s.createInstanceOfB();
C<int> s.createInstanceOfC();
return 0;
}